How to print a while() loop in PDO [closed]

笑着哭i 提交于 2019-12-25 06:36:50

问题


I have a database table with 4 columns: Name, Comment, Star, Status.

I want to display all the records of the table on a single page. Here is my query:

$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;

However, var_dump($reviews) displays array(0) { }. Where am I going wrong?


回答1:


You are accessing the array as an object with the -> operator , use [] instead.

$reviews = array();

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



回答2:


You are defining $reviews as array.

$reviews = array();

then how can you do this-

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

this way you do for object not array



来源:https://stackoverflow.com/questions/22881179/how-to-print-a-while-loop-in-pdo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!