无法将sql查询中的getted元素添加到数组中

时间:2014-03-26 12:05:29

标签: php mysql sql

function get_comment_count_for_events() {
    $query = "SELECT event_token , COUNT(NULLIF(event_token, '')) AS counts FROM comment GROUP BY event_token ORDER BY counts DESC;";

    $result = mysql_query($query);
    $comment_count = array();
    while ($row = mysql_fetch_array($query)) {
        $comment_count = $row;
    }
    if (!$result) {
        trigger_error('Invalid query: ' . mysql_error() . " in " . $query);
    }
    return $comment_count;
}

这是我的功能。

我在其他档案中使用它

foreach (get_comment_count_for_events() as $comment_count_event) {
    echo $comment_count_event['tiken_event'];
    echo $comment_count_event['count'];
}

但是在数据库中我测试查询它的工作: 结果: event_token - 计数

1 - 13

2 - 13

8 - 11

3 - 8

5 - 7

7 - 4

6 - 3

'' - 0

1 个答案:

答案 0 :(得分:1)

更新您的代码,您将覆盖$comment_count变量。你需要使用数组;

while ($row = mysql_fetch_array($result)) {
    $comment_count[] = $row;
}

同样在第二次迭代中,字段名称不正确。也更新它们;

foreach (get_comment_count_for_events() as $comment_count_event) {
    echo $comment_count_event['event_token'];
    echo $comment_count_event['counts'];
}