1

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],
2
  • you could use mysql group by clause Commented Jul 26, 2015 at 13:51
  • 1
    You are looking for group by, a fundamental part of SQL. You should learn the basics of SQL if you want to use databases at all effectively. Commented Jul 26, 2015 at 13:51

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.