MySQLi事务后insert_id返回0

4
我有以下代码:

<?php
    header('Content-Type: text/plain');
    $db = new mysqli('localhost', 'username', 'password', 'my_schema');
    $db->autocommit(false); // start transaction
    $sql = "INSERT INTO my_table (col1, col2) VALUES (1, 2)";
    $db->query($sql);
    // $last_id = $db->insert_id;
    // echo 'Last ID before commit: ' . $last_id . PHP_EOL;
    $db->commit();
    $db->autocommit(true); // end transaction
    $last_id = $db->insert_id;
    echo 'Last ID after commit: ' . $last_id . PHP_EOL;
    $db->close();
?>

以上代码的输出是:
Last ID before commit: 1 <-- if uncomment the 2 lines above, it will show this
Last ID after commit: 0

insert_idautocommit之外无法工作(返回0),即使它已经被正确提交和插入到数据库中。这是预期的行为吗?


1
由于 PDO::lastInsertId 似乎也表现出这种行为,我认为你是正确的。 - mpyw
2个回答

2

关于你的代码有几点需要注意:

  • 当你提交时,事务就结束了。一旦你提交,你可以:创建一个新的事务,将自动提交设置为true以恢复其默认行为,或关闭连接。
  • 在提交之前,你需要获取insert_id。这样做的原因是通常情况下,在进行事务时,你需要用到外键id。

-3

请试一下这个

$last_id = mysqli_insert_id($link);

$link 是使用 mysqli_connect(...) 返回的数据库对象。这将给出自增列中最后插入行的 id。


1
停止使用已弃用的 mysql_* 函数。改用 MySQLiPDO。这里有一个关于 PDO 的好教程:http://j.mp/PoWehJ。 - Raptor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接