eluong eluong - 7 months ago 34
PHP Question

MySQL: Count occurrences of distinct values error

I am trying to use code from the following old question:

MySQL: Count occurrences of distinct values

My query is as follows:

$result = $db->query("SELECT name,COUNT(*) as cnt FROM `table` GROUP BY name ORDER BY cnt DESC");
$row = mysqli_fetch_array($result);
var_dump($row);


In phpmyadmin this code will output all the name and COUNT columns. When I run
var_dump($row)
it will only have one row for me to work with (the first one, ie the one with the most occurrences), which I can't figure out why. Any ideas? Thanks.

Answer

From the documentation on mysqli_fetch_array:

Fetch a result row as an associative, a numeric array, or both

As you found out, it does just that: it fetches a row.

Maybe you were expecting the behaviour of mysqli_fetch_all?

Fetches all result rows as an associative array, a numeric array, or both