0

I just trying to save or insert data into a mysql from inside a custom module.

The table is 'my_table'.

I use this to insert:

  db_insert('my_table')->fields(array(
    'name' => 'Andy',
    'last_name' => 'Moore',

  ))->execute();

and this to update:

  db_update('my_table') 
  ->fields(array(
    'name' => 'John'
  ))
  ->condition('last_name', 'Moore')
  ->execute();

So far so good, but now I need to update or insert a value:

If 'name=George' exist then update its 'last_name=Niels'. Otherwise if  'name=George' doesn't exist then create insert it with this values 'name=George' and 'last_name=Niels'
  • I just need what Juraj has posted. I think that this line expose what I needed: "If 'name=George' exist then update its 'last_name=Niels'. Otherwise if 'name=George' doesn't exist then create insert it with this values 'name=George' and 'last_name=Niels'" – JPashs Feb 12 '16 at 9:01
2

You can use db_merge() function. Here is the example.

db_merge('my_table')
  ->insertFields(array(
    'name' => 'George',
    'last_name' => 'Niels',
  ))
  ->updateFields(array(
    'last_name' => 'Niels',
  ))
  ->key(array('name' => 'George'))
  ->execute();

If there is no key ("name") with value "George", "name" and "last_name" values are inserted to the database table. If there is a record with key value "George", only the field "last_name" is updated with the specified value.

| improve this answer | |

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