Php pdo rollBack() 不适用于更新语句
Posted
技术标签:
【中文标题】Php pdo rollBack() 不适用于更新语句【英文标题】:Php pdo rollBack() not working for update statement 【发布时间】:2018-05-17 15:08:37 【问题描述】:我使用 php PDO 事务。我有插入和更新语句,我想在 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() 将为插入和更新返回 1。但是对于空的 userId,rowCount() 将返回 0。如果 rowCount() 为 0,我将错误消息分配给 $error[]。如果 $error 不为空,它将捕获 Exception 并回滚所有 $userId 的事务。
我的预期结果是当 $error 不为空时,将抛出异常并在 catch 中回滚。它应该假设删除表支付中 userIds (1,2) 的记录,并更新回表 users 中 userIds (1,2) 的原始信用值。
我得到的结果是当代码到达 $pdo->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 );
【问题讨论】:
你的代码应该包含一个表创建查询和插入查询来填充它,这样每个人都可以确认行为。 How to create MCVE for a PDO related problem 不过是个疯狂的猜测。您的用户的表引擎确实是 InnoDB 吗? 是的,它是 InnoDB。感谢您的回复。 我已经添加了表格和插入查询。 您应该提供旨在一次性运行的完整代码。让一个人复制并粘贴它并获得结果。但是请确保您事先自己运行它,它实际上支持您声称某些表不会回滚 【参考方案1】:$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)
再次,快速检查显示数据没有变化,因此看起来整个过程都在正常运行
【讨论】:
这是为了抛出一个异常 - 一对故意不匹配的数组。 我刚刚在我这边测试过。更新仍然没有恢复到原始数据。你能改变这条线吗? from $sql = "update users set credit = credit + ? where id = ?"; $paymentAmounts = 数组(25,30,55,30,45,44,21); to $sql = "update users set credit = ? where id = ?"; $paymentAmounts = 数组(40,90,15,30,45,44,21);以上是关于Php pdo rollBack() 不适用于更新语句的主要内容,如果未能解决你的问题,请参考以下文章
pdo-odbc 不适用于绑定值,nvarchar 和 text 在等于运算符中不兼容
Laravel DB::rollback() 不适用于事务处理
lastInsertId() 在插入操作中不适用于 PDO 对象[关闭]