为什么获胜';t赢得了以下PDO交易';我不能用PHP


Why won't the following PDO transaction won't work in PHP?

我使用的是PHP 5.4.4版本,MySQL数据库使用InnoDB。我已经使用PDO有一段时间了,没有使用事务,一切都很完美。然后,我决定尝试实现事务,并且不断得到InternalServerError500。以下代码对我有效(不包含事务)。

try {
    $DB = new PDO('mysql:host=localhost;dbname=database', 'root', 'root');
    $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh = $DB->prepare("SELECT * FROM user WHERE username = :test");
    $dbh->bindValue(':test', $test, PDO::PARAM_STR);
    $dbh->execute();
}
catch(Exception $e) {
    $dbh->rollback();
    echo "an error has occured";
}

然后,我尝试将事务与以下代码一起使用(这不起作用)。

try {
    $DB = new PDO('mysql:host=localhost;dbname=database', 'root', 'root');
    $DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh = $DB->beginTransaction();
    $dbh->prepare("SELECT * FROM user WHERE username = :test");
    $dbh->bindValue(':test', $test, PDO::PARAM_STR);
    $dbh->execute();
    $dbh->commit();
}
catch(Exception $e) {
    $dbh->rollback();
    echo "an error has occured";
}

当我运行前面的代码时,我得到一个内部服务器错误500。

如有任何帮助,我们将不胜感激!谢谢

$DB->beginTransaction返回一个boolean,它不返回数据库处理程序(如在准备好的语句对象中)。。

请改用$dbh = $DB->prepare。您可以使用$DB->beginTransaction的返回值来检查事务是否成功启动(它将关闭自动提交模式)。

您需要引用数据库连接句柄,而不是beginTransaction方法的返回值。您正在将返回值分配给$dbh$无论如何都不需要dbh。您需要使用$DB变量,然后围绕PDO语句声明beginTransaction/commit。

//start transaction, reference PDO handle
$DB->beginTransaction();
//In between your beginTransaction and Commit is where you will put all of your
// statements.
$DB->prepare(...);
$DB->bindValue(...);
$DB->execute();
//commit your statements once done.
$DB->commit();