3

I have a module which creates records in the db via drupal_write_record and this works perfectly. However I need to get the automatically assigned serial number for each record which is written into a variable.

Does anyone know how I can achieve this and get the index #?

I need the index variable to use in another table to create the reference...

Edit: Clives answer worked as below:

// Create object
$call = new stdClass;  
$call->uid = $user->uid;
$call->call_type = $call_type;
$call->cli = $cli;
$call->start_nid = NULL;
$call->timestamp = $timestamp;

// Insert call row in db  
drupal_write_record($table,$call);

// Test correct index
drupal_set_message($call->call_id);

2 Answers 2

5

drupal_write_record() populates the serial field of an object you pass to it automatically. So assuming you have a serial field in your table called id, if you run code like the following:

$record = new stdClass;
$record->title = 'Title';
$record->some_other_field = 'Something';

drupal_write_record('table_name', $record);

the $record object will be auto-populated with a member representing the serial column when the function returns. In this example you can access it with $record->id.

4
  • 1
    Ahh seems to make more sense than my answer below. I will give it a try now. I think the docs are a little hard to follow..
    – WestieUK
    Commented Mar 14, 2012 at 11:49
  • I was using an array which doesnt seem to work with your method. However, I have just converting this to an object to test your method and it works. Are there any pro's and con's to using an object over an array with drupal_write_record()?
    – WestieUK
    Commented Mar 14, 2012 at 11:54
  • 2
    It won't work with an array because drupal_write_record() internally converts a passed array to an object. Then it does what it needs to with that object, then converts it back to an array for return. This means you lose the reference to the original array from the calling function, even though the parameter is itself passed by reference. Because of this I always use an object :)
    – Clive
    Commented Mar 14, 2012 at 12:00
  • This is one of those questions that can be answered by reading the source: api.drupal.org/api/drupal/includes%21common.inc/function/…
    – paul-m
    Commented Mar 14, 2012 at 13:09
0

Think I found the solution:

$last_id = db_last_insert_id($table, $field);

Edit: As per Clive's comments his solution above is most effective.

1
  • That will incur the cost of an extra database query, drupal_write_record() has already run that query for you so you might as well use that for performance reasons :)
    – Clive
    Commented Mar 14, 2012 at 11:49

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.