如何在PDO中打印while()循环 [英] How to print a while() loop in PDO
本文介绍了如何在PDO中打印while()循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含4列的数据库表:Name
,Comment
,Star
,Status
.
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;
但是,var_dump($reviews)
显示array(0) { }
.我要去哪里错了?
However, var_dump($reviews)
displays array(0) { }
. Where am I going wrong?
推荐答案
您正在使用->
运算符将数组作为对象访问,请改为使用[]
.
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'];
}
这篇关于如何在PDO中打印while()循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文