Reputation: 11576
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
?
Upvotes: 1
Views: 504
Reputation: 95900
@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
Upvotes: 3
Reputation: 3908
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.
Upvotes: 5
Reputation: 8858
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);
}
Upvotes: 5