下面是我的代码。当我使用事务时,事务被提交但第一个查询($receipt_query
)没有输入到数据库中,另外两个是。在没有事务的情况下运行查询时,所有查询都会成功运行。所以有人能在这里发现问题吗?!
$mysqli->autocommit(false);
if(!empty($_POST['receipt'])) {
$result = $mysqli->query("insert query 1");
if (!$result) {
$error = 'Some error message';
}
}
if (!empty($_POST['payment'])) {
$result = $mysqli->query("insert query 2");
if (!$result) {
$error = 'Some error message';
}
}
if(empty($error)) {
if($mysqli->query("query 3")) {
$mysqli->commit();
} else {
$mysqli->rollback();
}
} else {
$mysqli->rollback();
}
没有交易意味着"全部或没有"?那么,即使整个交易已经提交,第一个如何提交呢?
答案 0 :(得分:0)
您需要在自动提交后启动交易。
$mysqli->autocommit(false);
$mysqli->begin_transaction();
使用try-catch环绕代码:
try {
// First of all, let's begin a transaction
$mysqli->autocommit(false);
$mysqli->begin_transaction();
// A set of queries
$mysqli->query('first query');
$mysqli->query('second query');
$mysqli->query('third query');
// If we arrive here, it means that no exception was thrown
// i.e. no query has failed, and we can commit the transaction
$mysqli->commit();
} catch (Exception $e) {
// An exception has been thrown
// We must rollback the transaction
$mysqli->rollback();
}