1

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.

4

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.

db_merge('example')
  ->key(array('name' => $name))
  ->fields(array(
      'field1' => $value1,
      'field2' => $value2,
  ))
  ->execute();

by: dzutaro, tlyngej, stewart.adam, AndreyMaximov

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.