eluong eluong - 2 years ago 117
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);

In phpmyadmin this code will output all the name and COUNT columns. When I run
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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download