PDO rowCount未返回正确数量的受影响的行

时间:2012-03-01 01:20:49

标签: php pdo

我遇到PDO预处理语句的问题,而rowCount返回错误的受影响行数。

我有一个简单的测试数据库:

create table test (
   boolean var1;
);

然后我有以下测试代码:

$sth = $pdo->prepare("INSERT into test (var1) VALUES (:val)");
$sth->execute(array(':val' => true));
echo $sth->rowCount();

按预期返回:受影响的行数为

当我插入无效类型并且插入失败时:

$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

1 个答案:

答案 0 :(得分:2)

在我看来,$sth->execute(array(':val' => true))成功完成,从而增加了rowCount,但$sth->execute(array(':val' => 20))却没有。以下是每个阶段rowCount的{​​{1}}状态:

$sth

现在,让我们以相反的顺序看一下:

$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