Maroof Mandal
Maroof Mandal

Reputation: 531

How to count MySQL array values in PHP?

How to count MySQL array values? For example, the below code

$get = mysqli_query("SELECT * FROM clicks WHERE uid='$id'");
while($comp = mysqli_fetch_array($db, $get)) {
$country = $comp['country'];
echo "$country<br>";
}

will give output country names in the table country as

India
India
Pakistan
India
United States
Japan
United States
United States
India

I want to count the number of times each country appears in the table and store the values as:

 ['Country', 'Counts'],
 ['India', 4],
 ['Pakistan', 1],
 ['United States', 3],
 ['Japan', 1],

Upvotes: 1

Views: 909

Answers (1)

Samuel Cook
Samuel Cook

Reputation: 16828

Your SQL should read as

SELECT *,COUNT(*) as `count` FROM clicks WHERE uid='$id' GROUP BY `country`

Then you should be able to call the count paramenter:

while($comp=mysql_fetch_array($get)) {
    echo $comp['country'].': '.$comp['count'];
}

Side note: MySQL has been depricated. You should look to switch to MySQLi or PDO.

Upvotes: 2

Related Questions