By vvanaparthy on
db_last_insert_id() in Drupal is highly unpredictable, it asks for parameters but doesn't use it and if you have any other insert in node_save like path alias insertion it gives wrong results.
Don't rely on it, use your own logic
/**
* Returns the last insert id.
*
* @param $table
* The name of the table you inserted into.
* @param $field
* The name of the autoincrement field.
*/
function db_last_insert_id($table, $field) {
return db_result(db_query('SELECT LAST_INSERT_ID()'));
}
The way I achieved it
db_result(db_query("SELECT max(nid) from {node} WHERE type = 'va' AND uid = $user->uid"));
Thanks,
V
Comments
this code is not thread safe
selecting max(nid) will return incorrect result if another thread inserts to the same table between your insert and query for the id,
checking $user->uid will prevent that between two users but it's still possible in case insert is done by the same user.
LAST_INSERT_ID() on the other hand will always return correct id as long as it's called immediately after the insert that you are interested.
mysql doesn't provide 'last_insert_id' query where table and field are parameters.