2011-12-26 91 views
1

请考虑一个名为foo的表,其中有id (PRIMARY & AUTO_INCREMENT)列。我在这张桌上插入一行,挑战从这一点开始。依赖于“mysql_insert_id”

$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

回答

5

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); 
} 
+0

Thanks @Hemant;但是,如果$ query包含'INSERT'关键字“,那么我会立即在$ db-> query()'function”中存储'$ this-> last_insert_id'。 – 2011-12-26 10:53:08

+0

通过在查询中跳过使用id字段来尝试 – Dau 2011-12-26 10:55:00

4

http://dev.mysql.com/doc/refman/5.1/en/getting-unique-id.html更多的信息,所以这样说:

“对于LAST_INSERT_ID(),最近生成的在每个连接的基础上,服务器的ID号保持在 ,不会被另一个 客户端更改,如果您更新另一个AUTO_INCREMENT 列, onmagic值(也就是说,值不是NULL,并且不是0)。同时使用来自多个客户端的LAST_INSERT_ID()和AUTO_INCREMENT列 完全有效。每个客户端 将获得最后插入的ID的最后声明,客户 执行。”

所以你应该罚款做你想要什么,你不应该奇怪的结果。