How to insert/update data in database

by Ethan   Last Updated March 13, 2018 07:07 AM

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.

Tags : database

Answers 2

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

No Sssweat
No Sssweat
July 27, 2016 01:53 AM

March 13, 2018 06:56 AM

Related Questions

Drupal store into own database

Updated July 03, 2015 18:03 PM

Connect to Intersystems Cache DB via ODBC

Updated May 01, 2015 21:03 PM

drupal site is really slow on VPS server

Updated April 03, 2015 21:20 PM