mysqli的交易陈述

时间:2018-02-23 03:02:01

标签: php mysql

在mysqli中准备事务语句的正确语法是什么?我已经尝试过最接近的数字:

$conn->begin_transaction();
$stmt = $conn->prepare("INSERT INTO ARCHIVE_CLICKS_PATH SELECT * FROM CLICKS_PATH WHERE REFERER = ?");
$stmt->bind_param('i', $referer);
$stmt = $conn->prepare("DELETE FROM CLICKS_PATH WHERE REFERER = ?;");
$stmt->bind_param('i', $referer);
$stmt->close();
$conn->commit();

不会抛出错误,也似乎没有做任何事情。

编辑:我搜索了\在发布之前阅读上面发布的答案,它根本没有帮助我准备好mysqli语句语法(这似乎是问题)。没有抛出错误,当我直接将其输入数据库时​​,该语句正常工作。我可以毫无准备地使它工作得很好,但我无法在任何地方找到适合于mysqli预处理语句示例的bind_params \ execute \ commit的语法。

添加以下作品:

BEGIN;
INSERT INTO ARCHIVE_CLICKS_PATH SELECT * FROM CLICKS_PATH WHERE REFERER = 15;
DELETE FROM CLICKS_PATH WHERE REFERER = 15;
COMMIT;

当我直接将其输入数据库时​​。

2 个答案:

答案 0 :(得分:1)

您应该使用try catch block来抛出异常。见下面的例子:

$sql1 = "INSERT INTO ARCHIVE_CLICKS_PATH SELECT * FROM CLICKS_PATH WHERE REFERER = ?;";
$sql2 = "DELETE FROM CLICKS_PATH WHERE REFERER = ?;";
$stmt1 = $conn->prepare($sql1);
$stmt2 = $conn->prepare($sql2);
try{
    $conn->query('BEGIN;');
    if($stmt1 == false || $stmt2 == false || $stmt1->bind_param("i", $b) == false || $stmt2->bind_param("i", $a) == false || $stmt1->execute() == false || $stmt2->execute() == false){
        throw new Exception($conn->error);
    }
    else{
        echo "successful";
    }
    $conn->query('COMMIT;');
}
catch(Exception $e){
    $conn->query("ROLLBACK;");
    echo $e->getMessage();
}

答案 1 :(得分:0)

这是我根据上面的答案解决的问题,以防它对任何人有所帮助:

try
{
    $conn->autocommit(FALSE);
    $conn->begin_transaction();
    $stmt1=$conn->prepare("INSERT INTO ARCHIVE_CLICKS_PATH SELECT * FROM CLICKS_PATH WHERE REFERER = ?;");
    $stmt1->bind_param('i',$referer);
    if ($stmt1->execute() == false) {
        throw new Exception('Statement 1 Failed');
    }
    $stmt2=$conn->prepare("DELETE FROM CLICKS_PATH WHERE REFERER = ?;");
    $stmt2->bind_param('i', $referer);
    if ($stmt2->execute() == false) {
        throw new Exception('Statement 2 Failed');
    }

    $stmt1->close();
    $stmt2->close();
    $conn->commit();

}
catch(Exception $e)
{
    $conn->rollback();
    throw $e;
}