有人可以解释为什么下面的注释行作为常规查询正常工作,但是当我尝试使用prepare语句传递它时失败了吗?
(一个文件中的所有代码)
<?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;
.....
答案 0 :(得分:1)
PDOStatement::execute()
没有返回结果集,它只返回一个布尔值,指示查询是否成功。然后,您的代码会尝试在该布尔值上调用setFetchMode()
,这当然是无效的。
要获取查询结果,您需要调用其中一个PDOStatement::fetch*
方法。我怀疑你想做的是
while ($l = $stmt->fetchObject("Log"))
{
echo $l->getRow().'<br />';
}
也无需拨打setFetchMode()
。
(我承认我从未使用fetchObject()
,所以我可能没有完全正确的语法。)