PHP MySQL事务捕获错误

时间:2017-04-02 16:53:47

标签: php mysql transactions commit rollback

我一直在寻找两天,但仍未找到答案。假设我在PHP下面有代码:

 for (var i = 0; i < data.length; i++) {

                    var string = data[i].fields.author_name;
                    $("#offercontainer").append(
                        "<div class='offer'>" +
                        "<p class=offername>" + string + "</p>" +
                        "<p class=offertext> offered his " + " " + data[i].fields.item_name +  "</p>" +
                        "</div>"
                    );
                    appendUserImage(i,data[i].fields.author);
                }

我无法检查事务中的查询是否都成功,因为当我执行这些查询时,commit函数总是返回true。

如何检查事务中的所有查询是否成功?

2 个答案:

答案 0 :(得分:1)

执行此操作的常用方法:

$mysqli->begin_transaction();
try {
    mysqli_query($mysqli, "DELETE FROM Test WHERE ID=1");
    mysqli_query($mysqli, "DELETE FROM TEST WHEREE ID=2"); <-- THIS ONE WILL FAIL BECAUSE OF TYPO
    mysqli_query($mysqli, "DELETE FROM Test WHERE ID=3");
} catch (\Exception $e) {
    // this will show statement with error
    echo $e->getMessage();
    $mysqli->rollback();
    throw $e;
}
$mysqli->commit();

答案 1 :(得分:0)

您可以使用mysqli_error捕获错误。

$startTrans = 'START TRANSACTION;';  // Starting a mysql transaction
mysqli_query($conn, $startTrans); 

$query = 'Insert into students (roll_no,name,class) VALUES (101,"mathew","fourth")';
$result = mysqli_query($conn, $query);
if (mysqli_error($conn)) {
   // Rollback can be done here 
   mysqli_query($conn, "ROLLBACK;"); // All above queries will get rolled back
   die(mysqli_error($conn)); 
} else {
   mysqli_query($conn, "COMMIT;"); // changes will get saved to database
}