I use the function to insert or update records in a table, but sometimes I would like to know whether the function has executed an update or an insert. In my scenario I always provide the primary key:


The function inserts a record if $entry['key'] does not exists and updates the record with the new information otherwise.

Is there somewhere I can check to see what the function has done ?

  • You have to knownif the record exists or not. drupal_write_record tries to update the entry if you provide a key to second arg.
    – AKS
    Dec 22, 2012 at 17:37

2 Answers 2


Turns out that in order to know if the operation was an UPDATE or an INSERT you need to know whether the record existed or not before committing the transaction. This is not what drupal_write_record() does. This function just checks it's arguments and issues an update or an insert accordingly. So there is really no way to tell if the function did an INSERT or an UPDATE.

The solution is using db_merge() query, it is a relatively new SQL ANSI standard that does exactly what I needed (and in the case of MySQL does it in an atomic transaction).

$return_value = db_merge('mytable')
            ->key(array('id' => $key))
                'updatedon' => $now,

The return value is an integer returning 1 for inserts and 2 for updates.


drupal_write_record() returns


    Return status for saving which involved creating a new item.


    Return status for saving which involved an update to an existing item.

You can use that return value to determine what type of query was executed.

  • I've just re-read the question and I realise I've missed the point a bit. Why do you need to do this if you don't mind my asking?
    – Clive
    Dec 21, 2012 at 19:11
  • Thanks for your answer but I always provide the key. These objects are submitted through a web service, and in fact the function does it right,updating or inserting, I just want to know which one of them has been executed.
    – drcelus
    Dec 21, 2012 at 19:11
  • Yeah sorry I realised that a bit late :) The only way you'll get the information is by patching drupal_write_record()...what problem are you trying to solve? Maybe there's a creative way around it
    – Clive
    Dec 21, 2012 at 19:13
  • Just trying to load a lot of records, most of them may exist and some are new, but the data for the existing ones should be updated and if the records are new it should be noted in a log file. I can test every single record before updating but thought there is a better way.
    – drcelus
    Dec 21, 2012 at 19:16
  • We both need to learn to read the docs ;) See the updated answer
    – Clive
    Dec 21, 2012 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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