php - 无法显示使用 PDO 查询的结果

标签 php html mysql pdo

我正在尝试从查询中获取结果,该查询应该获取多个结果并将它们全部显示在页面上。但是它不显示任何内容。我的猜测是我的循环语法错误。但我不确定。

//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->e​​rrorInfo()

关于php - 无法显示使用 PDO 查询的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36504190/

相关文章:

PHP - 延迟重定向

PHPDoc:@return void 有必要吗?

php - cakephp 1.3 save() 返回 true 但数据库中没有保存任何内容

javascript - amcharts 子树在单击之前不应打开

mysql - SQL删除重复记录

php - 客户端和服务器的时间/日期差异?

php - DomPDF显示除最后一页外的数据表

html - 如何用一个 css 表引用多个 html 页面?

JavaScript 函数未在 Thymeleaf 中加载?

php - 每个 PHP 程序员都应该知道什么?