PDO rowCount不能返回正确的受影响行数

6

我遇到了一个问题,涉及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


1
只需为PDO打开异常并获得更好的处理方式即可。 - zerkms
1
这对我来说很有道理,因为你重新使用了相同的PDOStatement。如果你需要每个语句的单独rowCount,那就准备第二个语句。 - Ozzy
1个回答

2

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

$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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接