I want to save data in a mysql table database using drupal 7 (costume module), but my question is that depends if the value exists I have to use the UPDATE command and if not INSERT command but I don't know how to write this code with the db api.

1 Answer 1


Use db_merge

In the general sense, a Merge query is a combination of an Insert query and an Update query. If a given condition is met, such as a row with a given primary key already existing, then an Update query is run. If not, an Insert query is run.

Thus, db_merge adds it, if it doesn't exist yet. OR updates it, if it already exists.

  ->key(array('name' => $name))
      'field1' => $value1,
      'field2' => $value2,

by: dzutaro, tlyngej, stewart.adam, AndreyMaximov

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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