PDO将参数作为数组传递失败


PDO passing params as array fails

有人可以解释为什么下面的注释行作为常规查询工作正常,但当我尝试使用准备语句传递它时失败吗?

(所有代码都在一个文件中)

<?php
class Log {
    public $id;
    public $sensor;
    public $reading;
    public function getRow() {
        return $this->id.' '.$this->sensor.' '.$this->reading;
    }
}
try 
{
    $dbh = new PDO("mysql:host=localhost;dbname=homelog", "xxx", "yyy");
    //$rs = $dbh->query("SELECT * FROM logs WHERE id=1"); //WORKS FINE
    //PREPARE
    $stmt = $dbh->prepare("SELECT * FROM logs WHERE id= :x");
    $arr=array(':x'=>'1');
    $rs=$stmt->execute($arr);
    //END PREPARE
    $rs->setFetchMode(PDO::FETCH_INTO, new Log());
    foreach($rs as $l)
    {
        echo $l->getRow().'<br />';
    } 
    $dbh = null;
}
catch(PDOException $e)
{
    echo $e->getMessage();
}
?>

错误日志报告(感谢评论员):

[Wed Feb 24 00:05:59 2016] [error] [client 66.55.xxx.yyy] PHP Fatal error:  Call to a member function setFetchMode() on a non-object in /var/www/PiServer/testObj.php on line 24

更新代码以响应答案:

....
$dbh = new PDO("mysql:host=localhost;dbname=homelog", "root", "root");
    //$rs = $dbh->query("SELECT * FROM logs WHERE id=1"); //WORKS FINE
    //PREPARE
    $stmt = $dbh->prepare("SELECT * FROM logs WHERE id= :x");
    $arr=array(':x'=>'1');
    $rs=$stmt->execute($arr); //bool result value
    //END PREPARE
    $ret=$stmt->fetchObject("Log")
    foreach($ret as $l)
    {
        echo $l->getRow().'<br />';
    } 
    $dbh = null;
.....
PDOStatement::execute()

返回结果集,它只返回一个布尔值,指示查询是否成功。然后,您的代码尝试在该布尔值上调用setFetchMode(),这当然是无效的。

为了获得查询结果,您需要调用PDOStatement::fetch*方法之一。我怀疑你想做的是

while ($l = $stmt->fetchObject("Log"))
{
    echo $l->getRow().'<br />';
}

这也消除了调用setFetchMode()的需要。

(我承认我从来没有使用过fetchObject(),所以我的语法可能不完全正确。