gpt4 book ai didi

php - mysqli_commit 失败会自动回滚吗?

转载 作者:搜寻专家 更新时间:2023-10-31 20:35:20 24 4
gpt4 key购买 nike

我对 PHP 手册中这段代码的运行方式有一些疑问。我看到其他示例抛出异常(通常是面向对象的代码)或使用标志来跟踪每个单独查询的失败。

我的问题是为什么在决定提交或回滚之前必须标记错误并测试标记。查看下面的示例,似乎如果提交不起作用,则无论如何都不会提交任何查询。

我还注意到他们只是在提交失败时退出。这会自动回滚所有内容吗?

<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");

/* Insert some values */
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
if (!mysqli_commit($link)) {
print("Transaction commit failed\n");
exit();
}

/* close connection */
mysqli_close($link);
?>

最佳答案

Looking at the example below it appears that if the commit does not work, none of the queries would be committed anyway.

没错。

但重点是错误不仅可能发生在提交时。但是 - 更有可能 - 在执行其中一个查询时发生。 所以你需要检查不是只有提交结果,还有每个查询的结果并中止整个操作。

所以,你的问题应该读作

Does a mysqli failure automatically rollback?

答案是“是和否”。
默认情况下不会。
但是,如果您设法在查询失败时中止脚本,链接将关闭并且事务将自动回滚。下面的代码将 mysql 错误转换为 PHP fatal error ,如果其中一个查询失败,它将自动执行回滚。

<?php
/* set the proper error reporting mode */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$link = mysqli_connect("localhost", "my_user", "my_password", "test");

/* set autocommit to off */
mysqli_autocommit($link, FALSE);

/* Run your queries */
mysqli_query($link, "CREATE TABLE Language LIKE CountryLanguage");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Bavarian', 'F', 11.2)");
mysqli_query($link, "INSERT INTO Language VALUES ('DEU', 'Swabian', 'F', 9.4)");

/* commit transaction */
mysqli_commit($link);

/* this is the last line, NO other code is needed */

关于php - mysqli_commit 失败会自动回滚吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37038057/

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