Is there a way for db_insert() to overwrite existing entries?


As @kiamlaluno mentioned db_insert() inserts a new row in the table. You can use db_update(), to update the row if it already exists. You can use db_merge(), to combine both of them.
See the example (taken from the documentation):

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

In the above example, we instruct the query to operate on the "example" table. We then specify one key field, 'name', with a value of $name. We then specify an array of values to set.

If a row already exists in which the field "name" has the value $name, then fields field1 and field2 will be set to the corresponding values in that existing row. If such a row does not exist, one will be created in which name has the value $name, field1 has the value $value1, and field2 has the value $value2. Thus at the end of the query, the end result is the same regardless of whether or not the row already existed.

|improve this answer|||||
  • 1
    db_merge acts like an if statement for queries? It runs an update query if a row with that primary key value exists and an insert query if it doesn't? Am I understanding it correctly? – jsalita Aug 16 '13 at 0:51
  • @jsalita Stop on. It does exactly that. – AjitS Aug 16 '13 at 5:13

db_insert() inserts a new row in the table; if you need to update an existing row, you need to use db_update().

  ->fields(array('status' => 0))
  ->condition('type', 'module')
  ->condition('name', $module)

The fields passed to fields() are the ones that need to be updated.

|improve this answer|||||

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.