PHP - 将SQL GROUP BY作为数组返回?

时间:2013-12-12 16:38:08

标签: php mysql arrays mysqli group-by

我正在尝试使用GROUP BY作为数组返回MySQL查询。

我的表格如下:

user_id | type
--------------------
1       | test
1       | test
2       | test
1       | hello
1       | helloworld

我的代码和查询:

$number_of_workouts = array();
$query = mysqli_query(connect(),"SELECT type, COUNT(*) FROM `log` WHERE `user_id` = $user_id GROUP BY type");
$number_of_workouts = mysqli_fetch_assoc($query);

return $number_of_workouts;

上面的代码没有返回列出所有类型的数组,它只返回一种类型的数字(假设$user_id = 1

如何将查询结果作为数组返回?

2 个答案:

答案 0 :(得分:1)

mysqli_fetch_assoc($query);

从结果集中提取仅一行

如果您想要结果集中的所有行,则必须为每一行循环并将其添加到堆栈中,如:

$number_of_workouts = array();
$query = mysqli_query(connect(),
    "SELECT type, COUNT(*) AS count
     FROM `log`
     WHERE `user_id` = $user_id
     GROUP BY type"
);

$array = array();

while ($number_of_workouts = mysqli_fetch_assoc($query)) {
    $array[$number_of_workouts['type']] = $number_of_workouts['count'];
}

// Now you have all results like you want in the variable array:
print_r($array);

// print count of type test:
echo $array['test'];

或者您尝试mysqli_fetch_all()http://www.php.net/manual/en/mysqli-result.fetch-all.php

(对不起许多更新)

答案 1 :(得分:0)

您只在此处获取第一条记录。将提取语句保留在while循环中

        while($number_of_workouts = mysqli_fetch_assoc($query))
        {
            echo "<pre>";
            print_r($number_of_workouts);
        }