Php pdo rollBack()不适用于更新语句

时间:2017-12-04 07:32:43

标签: php mysql pdo transactions rollback

我使用PHP PDO事务。我有insert和update语句,我想在rowCount()返回0时回滚事务。请参阅下面的示例代码。

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '', array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false
));

$userIds = [1,2,""];
$paymentAmounts = [10.50,20.50,30.50];
$error = array();

$pdo->beginTransaction();

try
{
    foreach($userIds as $key => $userId )
    {
        $sql = "INSERT INTO payments (user_id, amount) VALUES (?, ?)";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(
                $userId, 
                $paymentAmounts[$key]
            )
        );

        if($stmt->rowCount() <= 0)
        {
            $error[] = ["Error occurred in userId: ".$userId];
        }

        $sql = "UPDATE users SET credit = ? WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->execute(array(
                $paymentAmounts[$key],
                $userId
            )
        );
        if($stmt->rowCount() <= 0)
        {
            $error[] = ["Error occurred in userId: ".$userId];
        }
    }
    if(!empty($error))
    {
        $displayError = implode(",", $error);
        throw new Exception($displayError);
    }

    // It should not reach here, if there is an error.
    $pdo->commit();

}
catch(Exception $e){
    echo $e->getMessage(); // displayError
    $pdo->rollBack(); // <<<==== It should rollback both Insert and Update to original state
}
?>

我有$ userIds数组。对于userId 1和2,rowCount()将为Insert和Update返回1。但是对于空userId,rowCount()将返回0.如果rowCount()为0,我将错误消息分配给$ error []。如果$ error不为空,它将捕获Exception并回滚所有$ userIds的事务。

我的预期结果是当$ error不为空时,将在catch中抛出异常和回滚。它应该假设删除userIds(1,2)的表付款中的记录,并在表用户中更新userIds(1,2)的原始信用值。

我得到的结果是当代码到达$ pdo-&gt; rollBack()时,它只从支付表中删除插入的记录,并且它没有将原始信用值更新回用户表中的userIds(1 ,2)。

您能否就代码的问题提出建议? 谢谢。

==========查询创建表和插入语句==========

-- CREATE TABLE "payments" -------------------------------
CREATE TABLE `payments` ( 
    `id` BigInt( 11 ) UNSIGNED AUTO_INCREMENT NOT NULL,
    `user_id` BigInt( 11 ) UNSIGNED NOT NULL,
    `amount` VarChar( 20 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
    PRIMARY KEY ( `id` ) )
CHARACTER SET = latin1
COLLATE = latin1_swedish_ci
ENGINE = InnoDB
AUTO_INCREMENT = 1;
-- -------------------------------------------------------------

-- CREATE TABLE "users" -------------------------------
CREATE TABLE `users` ( 
    `id` BigInt( 11 ) UNSIGNED AUTO_INCREMENT NOT NULL,
    `credit` VarChar( 20 ) CHARACTER SET latin1 COLLATE latin1_swedish_ci NOT NULL,
    PRIMARY KEY ( `id` ) )
CHARACTER SET = latin1
COLLATE = latin1_swedish_ci
ENGINE = InnoDB
AUTO_INCREMENT = 1;
-- -------------------------------------------------------------

INSERT INTO `users` ( `credit`, `id`) 
VALUES ( '5', 1 ),( '10', 2 ),( '15', 3 );

1 个答案:

答案 0 :(得分:2)

$dbport =   3306;
$dbhost =   'localhost';
$dbuser =   'root'; 
$dbpwd  =   'xxx'; 
$dbname =   'xxx';

$options=array( 
    PDO::ATTR_CURSOR                    =>  PDO::CURSOR_SCROLL,
    PDO::ATTR_PERSISTENT                =>  FALSE,
    PDO::MYSQL_ATTR_USE_BUFFERED_QUERY  =>  TRUE,
    PDO::MYSQL_ATTR_INIT_COMMAND        =>  'SET NAMES \'utf8mb4\' COLLATE \'utf8mb4_unicode_ci\', @@sql_mode = STRICT_ALL_TABLES, @@foreign_key_checks = 1'
);

$dsn='mysql:host='.$dbhost.';port='.$dbport.';dbname='.$dbname;
$dbo=new PDO( $dsn, $dbuser, $dbpwd, $options );


        $userIds = array(1,2,3,4,5,6);
        $paymentAmounts = array( 25,30,55,30,45,44 );

        try {

            $dbo->beginTransaction();

            if( count( $userIds )!=count( $paymentAmounts ) ) throw new Exception( sprintf('Unbalanced source arrays: $userids:%d, $paymentAmounts:%d',count( $userIds ),count( $paymentAmounts )));

            foreach( $userIds as $key => $userId ){

                $sql = "insert into payments ( user_id, amount ) values ( ?, ? )";
                $stmt = $dbo->prepare( $sql );
                if( $stmt ){
                    $stmt->execute( array( $userId, $paymentAmounts[ $key ] ) );
                    if( $stmt->rowCount() <= 0 ) throw new Exception( sprintf('Query #1 -> Error occurred in userId: %d count: %d', $userId, $stmt->rowCount() ) );
                } else {
                    throw new Exception( sprintf('Query #1 Prepare method failed @ %d for %d', $paymentAmounts[ $key ], $userId ) );
                }


                $sql = "update users set credit = credit + ? where id = ?";
                $stmt = $dbo->prepare( $sql );
                if( $stmt ) {
                    $stmt->execute( array( $paymentAmounts[ $key ], $userId ) );
                    if( $stmt->rowCount() <= 0 ) throw new Exception( sprintf('Query #2 -> Error occurred in userId: %d count: %d', $userId, $stmt->rowCount() ) );
                } else {
                    throw new Exception( sprintf('Query #2 Prepare method failed @ %d for %d', $paymentAmounts[ $key ], $userId ) );
                }
            }
            $dbo->commit();
        }catch( Exception $e ){
            echo 'Exception Raised: '.$e->getMessage();
            $dbo->rollBack();
        }

在测试1之前

mysql> select * from payments;
Empty set (0.00 sec)

mysql> select * from users;
+------+--------+
| id   | credit |
+------+--------+
|    1 | 0      |
|    2 | 0      |
|    3 | 0      |
|    4 | 0      |
|    5 | 0      |
|    6 | 0      |
+------+--------+
6 rows in set (0.00 sec)

在测试#1之后

mysql> select * from payments;
+----+---------+--------+
| id | user_id | amount |
+----+---------+--------+
|  1 |       1 | 25     |
|  2 |       2 | 30     |
|  3 |       3 | 55     |
|  4 |       4 | 30     |
|  5 |       5 | 45     |
|  6 |       6 | 44     |
+----+---------+--------+
6 rows in set (0.00 sec)

mysql> select * from users;
+------+--------+
| id   | credit |
+------+--------+
|    1 | 25     |
|    2 | 30     |
|    3 | 55     |
|    4 | 30     |
|    5 | 45     |
|    6 | 44     |
+------+--------+
7 rows in set (0.00 sec)

测试#2〜故意导致异常 - 使用此数据不匹配的数组长度:

        $userIds = array(1,2,3,4,5,6);
        $paymentAmounts = array( 25,30,55,30,45,44,21 );/* <----- extra item to cause exception */

这会导致异常:

Exception Raised: Unbalanced source arrays: $userids:6, $paymentAmounts:7

mysql> select * from users;
+----+--------+
| id | credit |
+----+--------+
|  1 | 25     |
|  2 | 30     |
|  3 | 55     |
|  4 | 30     |
|  5 | 45     |
|  6 | 44     |
+----+--------+
6 rows in set (0.00 sec)

与以前相同的数据 - 查询在异常后没有提交到db。

测试#3 - 带有假列名的软件查询

$sql = "update users set credit = boomerang + ? where id = ?";/* <----- ficticious column cause exception */

这会导致异常

Exception Raised: Query #2 -> Error occurred in userId: 1 count: 0

mysql> select * from users;
+----+--------+
| id | credit |
+----+--------+
|  1 | 25     |
|  2 | 30     |
|  3 | 55     |
|  4 | 30     |
|  5 | 45     |
|  6 | 44     |
+----+--------+
6 rows in set (0.00 sec)

同样,快速检查显示数据没有变化,因此看起来整个过程正常运作