How do I get last inserted record ID? I want to get the record ID for the last inserted row in a database table. I am trying to use db_last_insert_id(), but it is throwing an exception.


  Call to undefined function db_last_insert_id()


How do I get last inserted record ID?
In Drupal 6 you would use code similar to the following.

db_query("INSERT INTO {mytable} (intvar, stringvar, floatvar) VALUES (%d, '%s', %f)", 5, 'hello world', 3.14);
$id = db_last_insert_id('mytable', 'id_fieldname');


The Drupal 7 equivalent code is the following.

$id = db_insert('mytable')
  -&gt;fields(array(
    'intvar' =&gt; 5,
    'stringvar' =&gt; 'hello world',
    'floatvar' =&gt; 3.14,
  ))
  -&gt;execute();