[英]Relying on “mysql_insert_id”
考虑一个名为foo
的表,该表具有id (PRIMARY & AUTO_INCREMENT)
列。 我正在向该表中插入一行,挑战从这一点开始。
$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);
}
我在插入查询后立即调用它,并在获取last_insert_id
同时使用确切的当前连接链接,但不知道它有多重要(?)。
$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);
}
我应该担心依赖mysql_insert_id
实现吗?
last_insert_id应该是一个函数,它将返回插入的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);
}
查看http://dev.mysql.com/doc/refman/5.1/en/getting-unique-id.html以获得更多信息,它说:
“对于LAST_INSERT_ID(),最新生成的ID会在每次连接的基础上保留在服务器中。它不会被另一个客户端更改。即使您使用非魔法值更新另一个AUTO_INCREMENT列也不会更改(即,一个不为NULL且不为0的值。同时从多个客户端使用LAST_INSERT_ID()和AUTO_INCREMENT列是完全有效的。每个客户端都将收到该客户端执行的最后一条语句的最后插入的ID。”
因此,您应该做自己想做的事情就可以了,并且不会得到奇怪的结果。
@安东是正确的。 想要添加以下内容。
在事务中使用时,必须在提交前调用mysql_insert_id()。 否则,它将返回不可预测的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.