Home > Database > Mysql Tutorial > How to Properly Increment Values in MySQL UPDATE Queries?

How to Properly Increment Values in MySQL UPDATE Queries?

DDD
Release: 2024-12-29 16:55:14
Original
619 people have browsed it

How to Properly Increment Values in MySQL UPDATE Queries?

Incrementing Values in MySQL Update Queries

When attempting to increment a value in a MySQL update query, you may encounter issues if you use the approach presented in the code snippet provided. The code:

mysql_query("
    UPDATE member_profile 
    SET points= ' ".$points." ' + 1 
    WHERE user_id = '".$userid."'
");
Copy after login

does not correctly increment the existing points value. Instead of adding one to the current value, it simply sets it to 1.

Solution

To correctly increment the points value, you need to use MySQL's built-in increment operator. The modified code below increments the points column by 1:

$sql = "UPDATE member_profile SET points = points + 1 WHERE user_id = ?";
$db->prepare($sql)->execute([$userid]);
Copy after login

This code will work with both the PDO (PHP Data Objects) and mysqli (MySQL Improved Extension) database libraries in modern PHP versions.

The above is the detailed content of How to Properly Increment Values in MySQL UPDATE Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template