Home >Database >Mysql Tutorial >How to Correctly Increment a Value in a MySQL UPDATE Query?
Incrementing Value in MySQL Update Query
You've encountered an issue while trying to increment a value in your MySQL update query. Your code:
mysql_query(" UPDATE member_profile SET points= '" . $points . "' + 1 WHERE user_id = '" . $userid . "' ");
is not incrementing the points column as expected. Instead, it resets the value to 1.
Solution
The correct way to increment a value in a MySQL update query is by simply incrementing the existing value in the database. Here's the corrected code:
$sql = "UPDATE member_profile SET points = points + 1 WHERE user_id = ?"; $db->prepare($sql)->execute([$userid]);
This code uses prepared statements, which is a more secure and efficient way to execute SQL queries. It increments the points column by 1 for the specified user_id.
Additional Considerations
The above is the detailed content of How to Correctly Increment a Value in a MySQL UPDATE Query?. For more information, please follow other related articles on the PHP Chinese website!