问题
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