回滚功能在PHP中无法正常工作?

时间:2019-01-29 15:50:53

标签: php mysqli transactions rollback

我已经写了一条代码输入记录,如果输入的第一条记录只能输入第二条记录,如果第二条记录比第一条记录失败则将回滚并且不应该更改

<?php
include '../function.php';
// Set autocommit to off
mysqli_autocommit($mysqli,FALSE);
// Insert some values 
$a=mysqli_query($mysqli,"INSERT INTO test VALUES ('10','2')");
if($mysqli->affected_rows > 0)
{
    $b=mysqli_query($mysqli,"INSERT INTO test VALUES ('7','2')");
    if($mysqli->affected_rows > 0){
        mysqli_commit($mysqli);   
        echo "commited";
    }
    else{
        mysqli_rollback($mysqli);
        echo "rollback";
    }    
}else{
        echo "nothing";
}
// Close connection
mysqli_close($mysqli);

但是如果第二条记录无法保存,上面的代码将使我的第一条记录回滚。

1 个答案:

答案 0 :(得分:0)

建议您使用begin_transaction并尝试catch函数。下面是示例:

    $link = mysqli_connect("127.0.0.1", "my_user", "my_password", "sakila");

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
try {
    mysqli_begin_transaction($link, MYSQLI_TRANS_START_READ_WRITE);

    mysqli_query($link, "Insert statement 1");
    mysqli_query($link, "Insert statement 2");
    mysqli_commit($link);
    } catch (Exception $e) {
        mysqli_rollback();
    }