如何在PDO中打印while()循环

时间:2014-04-05 12:54:43

标签: php mysql pdo

我有一个包含4列的数据库表:NameCommentStarStatus

我想在一个页面上显示表格的所有记录。这是我的疑问:

$sth = $this->db->prepare("SELECT * FROM comment WHERE status = 1");
$sth->setFetchMode(PDO::FETCH_ASSOC);
$sth->execute();

$reviews = array();

while($row = $sth->fetch()){    
    $reviews->name = $row['name'];
    $reviews->comment = $row['comment'];
    $reviews->star = $row['star'];
}

return $reviews;

但是,var_dump($reviews)会显示array(0) { }。我哪里错了?

2 个答案:

答案 0 :(得分:1)

您正在使用->运算符作为对象访问数组,而是使用[]

$reviews = array();

while($row = $sth->fetch()){    
    $reviews[]['name'] = $row['name'];            # <---- Change them like this.
    $reviews[]['comment'] = $row['comment'];
    $reviews[]['star'] = $row['star'];
}

答案 1 :(得分:0)

您将$ reviews定义为数组。

$reviews = array();

然后你怎么做 -

$reviews->name = $row['name'];

这样你就可以为对象而不是数组