5

I am converting some module from d5 to d7, and in old code there is an update query like this:

<?php
db_query("UPDATE {a_table} SET count = count + 1 WHERE field1 = %d", $some_value);

As we see, it is incrementing a field value (AFAIK it is a mysql feature). But, if I use new style of update it won't work.

<?php
db_update('a_table')
    ->fields(array('count' => 'count + 1',))
    ->condition('field1', $some_value)
    ->execute();

Are there any workaround within new style of db update without running an extra query to get existing field value to increment it?

19

You can do it by adding an expression to the query:

db_update('a_table')
  ->expression('count', 'count + 1')
  ->condition('field1', $some_value)
  ->execute();
  • Just noting, this also works in Drupal 8 – David Thomas Oct 2 '18 at 8:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.