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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
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