Insert or Update value in table mysql? 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')-&gt;fields(array(
    'name' =&gt; 'Andy',
    'last_name' =&gt; 'Moore',

  ))-&gt;execute();


and this to update:

  db_update('my_table') 
  -&gt;fields(array(
    'name' =&gt; 'John'
  ))
  -&gt;condition('last_name', 'Moore')
  -&gt;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'
You can use db_merge() function. Here is the example.

db_merge('my_table')
  -&gt;insertFields(array(
    'name' =&gt; 'George',
    'last_name' =&gt; 'Niels',
  ))
  -&gt;updateFields(array(
    'last_name' =&gt; 'Niels',
  ))
  -&gt;key(array('name' =&gt; 'George'))
  -&gt;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.