mysqli_commit 失败会自动回滚吗?

Does a mysqli_commit failure automatically rollback?

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

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

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

<?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?

答案是"yes and no"。
默认情况下不会。
但是,如果您设法在查询失败时中止脚本,link 将关闭并且事务将自动回滚。下面的代码将 mysql 错误转换为 PHP 致命错误,如果其中一个查询失败,它将自动执行回滚。

<?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 */