PDO错误:$pdo->prepare()->execute()抛出错误"在布尔值上调用成员函数fetch() "



如果我的pdo查询像:

$sql=$pdo->prepare('select timezone from wo_users where user_id=?')->execute(array($wo['user']['user_id']));
while($row=$sql->fetch()){var_dump($row);die;}

将抛出错误:

(!(致命错误:调用成员函数中布尔值的fetch((C: 第27行上的\wamp64\www\community.voance\2\sources\calendar.php

但是如果我的直接使用query((的pdo查询不会抛出错误:

$sql=$pdo->query('select timezone from wo_users where user_id=1;');
while($row=$sql->fetch()){var_dump($row);die;}

C:\wamp64\www\community.voance\2\sources\calendar.php:27:array(大小=1("时区"=>字符串"-8'(长度=2(

为什么会发生这种情况?谢谢

您需要一个PDOStatement来获取,execute只返回true或false。您应该只使用executePDOStatement。这将返回一个可以fetch的结果对象或一个错误。有关PDO错误处理,请参阅My PDO Statement dons';不起作用。

$stmt = $pdo->prepare('select timezone from wo_users where user_id=?');
$stmt->execute(array($wo['user']['user_id']));
while($row = $stmt->fetch()){
var_dump($row);
die;
}

正如您从手动查询中看到的那样,工作原理是:

PDO::query((返回一个PDOStatement对象,失败时返回FALSE。

其中as执行:

成功时返回TRUE,失败时返回FALSE。

prepare是我们需要的:

如果数据库服务器成功准备语句,PDO::prepare((将返回一个PDOStatement对象。如果数据库服务器无法成功准备语句,PDO::prepare((将返回FALSE或发出PDOException(取决于错误处理(。

和fetch(这是描述,而不是返回(:

从与PDOStatement对象关联的结果集中获取一行

相关内容

最新更新