首页 > 解决方案 > 如何正确执行交易?

问题描述

我对 php/mysqli 编码并不陌生,但我以前从未真正使用过事务。我发现有关如何正确启动和执行事务的信息相互矛盾。我见过一些人使用autocommit(false),其他人只使用begin_transaction();,其他人说只在运行检查后提交,但其他人说如果有错误提交不会运行......我真的很困惑什么是正确的语法是。任何帮助表示赞赏!

//turn autocommit off and start transaction
$mysqli->autocommit(false);
$mysqli->begin_transaction();

//declare queries and make sure they all run properly
$result1 = $mysqli->query(myqueryhere);
if(!$result1) { $error[] = true; }

$result2 = $mysqli->query(mysecondqueryhere);
if(!$result2) { $error[] = true; }

$result3 = $mysqli->query(mythirdqueryhere);
if(!$result3) { $error[] = true; }

//only commit if there are no errors
if(empty($error)) {
$mysqli->commit();
}
//turn autocommit back on for future queries
$mysqli->autocommit(true);

标签: phpmysqlitransactionscommitautocommit

解决方案


推荐阅读