Php mysqli事务仅提交部分查询

Php mysqli事务仅提交部分查询,php,mysql,transactions,Php,Mysql,Transactions,下面是我的代码。当我使用transaction时,事务被提交,但是第一个查询$receipt\u查询没有输入到DB中,其他两个都是。在没有事务的情况下运行查询时,所有查询都会成功运行。有人能在这里发现问题吗 $mysqli->autocommit(false); if(!empty($_POST['receipt'])) { $result = $mysqli->query("insert query 1"); if (!$result) { $err

下面是我的代码。当我使用transaction时,事务被提交,但是第一个查询$receipt\u查询没有输入到DB中,其他两个都是。在没有事务的情况下运行查询时,所有查询都会成功运行。有人能在这里发现问题吗

$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();
}

交易不是意味着全部还是全部?那么,为什么即使整个事务已提交,第一个事务也没有提交?

您需要在自动提交后启动事务

$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();
}

你检查过mysql错误日志吗?我通常在php中检查,查询中没有错误,否则会触发rollback语句。我还将查看日志,尽管mysql错误日志中没有任何错误,也许您的$_POST['receive']是空的;因为当一个查询提交被调用时,它应该提交所有缓冲查询,但是我在有事务和没有事务的情况下运行相同的东西,但是在有事务的情况下,只插入了其中的两个。如果没有事务,所有mysqli::autocommit都是使用begin\u事务的替代方法。