下面是我的代码。当我使用transaction时,事务被提交,但第一个查询($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();
}事务是否意味着“全部或无”?那么,为什么即使整个事务都已提交,第一个事务也不会提交呢?
发布于 2014-06-05 00:59:14
您需要在自动提交后启动事务。
$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();
}https://stackoverflow.com/questions/24041595
复制相似问题