gpt4 book ai didi

php - 将 foreach 添加到数据库查询中

转载 作者:行者123 更新时间:2023-11-30 00:01:37 25 4
gpt4 key购买 nike

我试图显示所有类别和计数,但一次只能显示一个。

$query = $db->write_query('
SELECT c.*, COUNT(n.id) AS count
FROM ' . TABLE_PREFIX . 'newscategories c
LEFT JOIN ' . TABLE_PREFIX . 'news n ON FIND_IN_SET (c.cid, n.cid)
GROUP BY c.cid
ORDER BY count DESC
');

while($fetch = $db->fetch_array($query))
{
$name = $fetch['name'];
$count = $fetch['count'];
}



echo $name;

这只会打印一个。试图将它们全部打印出来。

最佳答案

您可以按照其他人的建议在循环内回显名称

while($fetch = $db->fetch_array($query))
{
$name = $fetch['name'];
$count = $fetch['count'];
echo $name . " " . $count ."<br />";

}

或者将返回的数据保存在数组中,然后循环遍历该数组

$results = array()
while($fetch = $db->fetch_array($query))
{
$results[] = array( 'name' => $fetch['name'],
'count' => $fetch['count']);
}

foreach ($results as $result){
echo $result['name']. " " . $result['count'] ."<br />";
}

关于php - 将 foreach 添加到数据库查询中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24984884/

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