gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:04:44 25 4
gpt4 key购买 nike

我有一个包含 4 列的数据库表:Name , Comment , Star , Status .

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

$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) { } 。我哪里出错了?

最佳答案

您要使用 -> 运算符将数组作为对象访问,请改用 []

$reviews = array();

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

关于php - 如何在 PDO 中打印 while() 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22881179/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com