Increment integer field in database when WHERE needs to be dynamic [closed]
题
I have a database column called "upvotes". I have another column called "userid".
I would like to increment the value in the "updates" column where the userid matches the dynamic variable I'm providing.
Here's my attempt:
$results = $wpdb->query("UPDATE points SET upvotes = upvotes + 1 WHERE userid= %d", $theDynamicUserID);
That is giving the following error:
[You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '%d' at line 1]<br /><code>UPDATE points SET upvotes = upvotes + 1 WHERE userid= %d</code>
EDIT: These Stack Exchange posts seem to hint that it's possible but I can't get the syntax right: https://stackoverflow.com/questions/973380/sql-how-to-increase-or-decrease-one-for-a-int-column-in-one-command
https://stackoverflow.com/questions/2259155/increment-value-in-mysql-update-query
解决方案
Just noticed that you are missing a prepare.
Your code should look like this
$results = $wpdb->query($wpdb->prepare('UPDATE points SET upvotes = upvotes + 1 WHERE userid= %d', $theDynamicUserID));
其他提示
EDIT: Seems like this is a bad idea:
I seem to have solved this by constructing the query first like this:
$theQuery = "UPDATE points SET upvotes = upvotes + 1 WHERE userid = '".$theDynamicUserID."'";
$results = $wpdb->query($theQuery);