简体   繁体   中英

Relying on “mysql_insert_id”

Think a table called as foo , which has id (PRIMARY & AUTO_INCREMENT) column. I'm inserting a row to this table and challenge starts at this point.

$db->query("INSERT INTO `foo` (id, row1, ...) VALUES('', '$row1', ...)");
if (!$db->is_error && $db->last_insert_id) {
   $id = $db->last_insert_id;
   do_really_important_things_with_last_ID($id);
   do_another_important_things_with_last_ID($id);
   ...
   do_ ... with_last_ID($id);
   do_ ... with_last_ID($id);
}

I'm calling it immediately after insert query and using exactly current connection link while getting last_insert_id , but do not know how does it matter(?).

$this->dbh = @mysql_connect(.....);
...
// query function
$this->result = @mysql_query($query, $this->dbh);
...
if (preg_match("/insert/i", $query)) {
   $this->last_insert_id = @mysql_insert_id($this->dbh);
}


Should I worry about this implementation relying on mysql_insert_id ?

last_insert_id should be a function, that will return inserted id

function last_insert_id(){
 return @mysql_insert_id();
}

if (!$db->is_error && $db->last_insert_id()) {
   $id = $db->last_insert_id();
   do_really_important_things_with_last_ID($id);
   do_another_important_things_with_last_ID($id);
   ...
   do_ ... with_last_ID($id);
   do_ ... with_last_ID($id);
}

Look at http://dev.mysql.com/doc/refman/5.1/en/getting-unique-id.html for more information, it says this:

"For LAST_INSERT_ID(), the most recently generated ID is maintained in the server on a per-connection basis. It is not changed by another client. It is not even changed if you update another AUTO_INCREMENT column with a nonmagic value (that is, a value that is not NULL and not 0). Using LAST_INSERT_ID() and AUTO_INCREMENT columns simultaneously from multiple clients is perfectly valid. Each client will receive the last inserted ID for the last statement that client executed."

So you should be fine doing what you want and you shouldn't get strange results.

@Anton is correct. Wanted to add the following.

When used in transactions, mysql_insert_id() MUST be called before committing. Otherwise, it will return unpredictable results.

Courtesy http://php.net/manual/en/function.mysql-insert-id.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM