Increment value (value = value+1) of $wpdb->update

This sql query

$wpdb->query("UPDATE log SET total=total+1 WHERE id='1')");

How do I turn it into $wpdb->update() statement?

Read More

Ex.

$wpdb->update('log', array('total'=>'total+1'), array('id'=>'1'));

Related posts

Leave a Reply

2 comments

  1. You don’t. Not with the WPDB update() function. The update function assumes that the values of the columns are strings. You can override that with the format parameter, but that only allows %d, %f, and %s (integer, float, string). It doesn’t allow operations on columns like total+1.

    You’d have to use the query() function directly to do your update.

  2. By using the query method, you may risk a sanitization problem. By using the update method, you risk a race condition. To overcome both, just before update issue a select on the row with a final clause “FOR UPDATE”. For fetching the results you can use the same condition which you are going to use for update and get_row method.

    The only caveat being if your condition hits multiple rows, there is no other way than to use query method of wpdb.