PDO准备的语句和rowCount返回的受影响行数不正确,我遇到问题。
我有一个简单的测试数据库:
create table test (
boolean var1;
);
然后我有以下测试代码:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
$sth->execute(array(':val' => true));
echo $sth->rowCount();
按预期返回:1行影响
当我插入一个无效类型并且插入失败时:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
$sth->execute(array(':val' => 20));
echo $sth->rowCount();
按预期返回:0行影响
然而,当我有多个插入-
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
$sth->execute(array(':val' => true));
echo $sth->rowCount() . ", ";
$sth->execute(array(':val' => 20));
echo $sth->rowCount();
结果为:1,1
如果我翻转执行顺序,我会得到:0,1
为什么在成功语句之后的失败语句中,rowCount()--受影响的行没有设置为零?
我正在运行php 5.3.6-13和Postgresql 9.1
在我看来,$sth->execute(array(':val' => true))
成功完成,从而增加了rowCount
,但$sth->execute(array(':val' => 20))
没有。以下是每个阶段$sth
的rowCount
的状态:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
# No successful DML queries have been done with the $sth yet.
# rowCount == 0
$sth->execute(array(':val' => true));
echo $sth->rowCount() . ", ";
# rowCount increases because of a successful INSERT statement
# rowCount == 1
$sth->execute(array(':val' => 20));
echo $sth->rowCount();
# rowCount does not increase due to failed INSERT statement
# rowCount == 1
现在,让我们按相反的顺序来看:
$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
# No successful DML queries have been done with the $sth yet.
# rowCount == 0
$sth->execute(array(':val' => 20));
echo $sth->rowCount();
# rowCount does not increase due to failed INSERT statement
# rowCount == 0
$sth->execute(array(':val' => true));
echo $sth->rowCount() . ", ";
# rowCount increases because of a successful INSERT statement
# rowCount == 1