我正在尝试从查询中获取结果,该查询应该获取多个结果并将它们全部显示在页面上。但是它不显示任何内容。我的猜测是我的循环语法错误。但我不确定。
//query to find comments about this map
$query = "
SELECT
user_id,
comment
FROM map_comments
WHERE
map_id = :mapID
";
//query parameters
$query_params = array(
':mapID' => $_SESSION['mapID']
);
try
{
//execute query
$statement = $db->prepare($query);
$result = $statement->execute($query_params);
//get all results
$comments = $result->fetchAll;
if($result === FALSE)
{
die(mysql_error()); // TODO: better error handling
}
}
catch(PDOException $e)
{
die("failed to find comments");
}
foreach($comments as &$comment)
{
echo $comment;
}
最佳答案
在函数后面需要括号来调用它。
$comments = $result->fetchAll;
应该是:
$comments = $statement->fetchAll();
此外,对 if ($result == FALSE)
的检查应位于此行之前。如果您使用 PDO,则不能使用 mysql_error()
,您应该使用 $statement->errorInfo()
。或者您应该在连接上启用 PDO::ERRMODE_EXCEPTION
,并且将调用 catch
block 。然后,您应该在打印的错误消息中使用 $db->errorInfo()
。
关于php - 无法显示使用 PDO 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504190/