| 6 database.mysql-common.inc | db_last_insert_id($table, $field) |
| 6 database.pgsql.inc | db_last_insert_id($table, $field) |
Returns the last insert id.
Parameters
$table: The name of the table you inserted into.
$field: The name of the autoincrement field.
Related topics
11 calls to db_last_insert_id()
File
- includes/
database.mysql-common.inc, line 540 - Functions shared between mysql and mysqli database engines.
Code
function db_last_insert_id($table, $field) {
return db_result(db_query('SELECT LAST_INSERT_ID()'));
}
Login or register to post comments
Comments
This has been deprecated in
This has been deprecated in Drupal 7 due to the fact that db_insert() returns the inserted id of the query. Just wanted to leave that here for anyone else trying to figure out what to replace this with in D7. See http://drupal.org/node/369520#comment-1240413
But it *does* work?
I keep reading how this function does not work in MySQL when you specify the table and field name.
The confusing thing for me though is that it does work in MySQL.
Without the table & field arguments I get the query insert ID. But with them, yes - I get the last insert ID according to that primary key field. Why does all documentation say that this doesn't work? Or maybe I'm just really lucky?
It only works for the very last ID
Yes Todd you seem lucky.
In MySQL it seems to return the very last inserted ID, regardless in which table and field.
So when a node was created and then a comment,
db_last_insert_id('node', 'nid');will return the comment id...
These parameters are irrelevant for MySQL
It seems that the function needn't the parameters, but you must passing them. It returns the mysql LAST_INSERT_ID function result which is the last inserted id in the active connection (any table), but not from table passed by parameter.
I think that this method does
I think that this method does work. You need to call it right after you execute the query and also check that the query did execute with no error. After reading the threads and having my own experience, I also thought this method wasn't working. I was periodically getting incorrect id's back, but then I realized that the id's were incorrect only because my query was sometimes failing. Perhaps this is the case for others seeing this issue. I noticed that node_save and just about any module that uses write_record method will indirectly use db_last_insert_id. If this method were broken, many things within drupal would not be working.