将foreach添加到db查询中

时间:2014-07-27 19:40:05

标签: php mysql

我正在尝试显示所有类别和计数,但我一次只能获得一个。

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

这只打印一张。试图让所有这些都打印出来。

3 个答案:

答案 0 :(得分:0)

在循环内打印。

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

    echo "$name: $count\n";
}

答案 1 :(得分:0)

您只有echo一个值:

echo $name;

每次循环运行时,它都会覆盖该变量,因此您只能打印最后一个值。听起来你想在循环内部打印值:

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

(注意:从这个起点开始,您可能希望改进输出格式,减少不必要的代码等。)

答案 2 :(得分:0)

您可以像其他人建议的那样回显循环内的名称

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 />";
}