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

How to Properly Increment Values in MySQL UPDATE Queries?

DDD
DDDOriginal
2024-12-29 16:55:14625browse

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."'
");

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]);

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!

Statement:
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