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?

up vote 17 down vote accepted

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

db_update('a_table')
  ->expression('count', 'count + 1')
  ->condition('field1', $some_value)
  ->execute();

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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