gpt4 book ai didi

php - MySQLi insert_id 事务后返回0

转载 作者:行者123 更新时间:2023-11-29 01:05:30 25 4
gpt4 key购买 nike

我有以下代码:

<?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),即使它已正确提交并插入到数据库中。这是预期的行为吗?

最佳答案

关于您的代码的几件事:

  • 事务在您提交时结束。提交后,您可以:创建新事务,将自动提交设置为 true 以恢复其默认行为,或关闭连接。
  • 您需要在提交之前获取 insert_id。之所以有一种奇怪的感觉,是因为通常,当您进行交易时,您需要外键的 ID。

关于php - MySQLi insert_id 事务后返回0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22032024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com