1

I have this MySQL selection query :

SELECT country, COUNT(*) 
  FROM $database 
  GROUP BY country

The output is an associative array with many rows and two columns: [country],[COUNT(*)]

Now I would like to print them out all BUT with

 if (count($results) > 0) {
    for($x = 0; $x < $arrlength; $x++) {
      echo "country: " . $results[$x]->country. "<br>";
      echo "reads:   " . $results[$x]**[COUNT()]**. "<br>";
    }
 } else {
    echo "0 results";
 }

It seems the code does not recognize COUNT(*) as column name and get no results. How can I access this second column values?

zachu
  • 671
  • 2
  • 7
  • 19
giro_2000
  • 11
  • 1
  • I realize editor missed " * " in betwenn COUNT commas .... maybe something similar occurs to my PHP code ? – giro_2000 Mar 10 '16 at 13:49

2 Answers2

1

Add alias (name) to your query field for COUNT(*) like:

SELECT country, COUNT(*) as my_count FROM $database GROUP BY country

and call it in your php code by name:

 if (count($results) > 0) {
    for($x = 0; $x < $arrlength; $x++) {
    echo "country: " . $results[$x]->country. "<br>";
    echo "reads:   " . $results[$x]->my_count. "<br>";
    }
    } else {
    echo "0 results";
 }
Alex
  • 16,739
  • 1
  • 28
  • 51
0

$results[$x]->country is object notation. Is $results[$x] an array or an object? They are not the same thing. I'm not sure what $results[$x]**[COUNT()]** is meant to be but adding asterisks around the key will definitely break things.

For array, you can use:

$results[$x]['COUNT(*)']

or for object:

$results[$x]->{'COUNT(*)'}

COUNT(*) should be a valid key for either but you need to enclose it in quotes.