The question:
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
The Solutions:
Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.
Method 1
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));
Method 2
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);
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0