Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count how many of each value from a field with MySQL and PHP

Tags:

php

mysql

count

I've seen that question several times but I can't find out how to display the result. I have a movie database and I would like the count of each genre of movie in my top menu in a single MySQL query so my menu would display like this:

Total Movies (300)
Drama (50)
Comedy (75)
Thriller (30)
...and so on...

I've found some MySQL query on this site but no one specify HOW to handle the counts after the SQL query. Something like this would probably work:

select genre, count(*) from movies group by genre

But how do I display the count for each value afterwards? Thank you very much!

like image 801
Andrewww Avatar asked Mar 25 '23 09:03

Andrewww


2 Answers

Alias the count part so you have an easily accessible column name:

SELECT genre, count(*) AS nb_movies FROM movies GROUP BY genre

then you can access it like $row['nb_movies'].

Without the alias the aggregate column takes the name of the aggregate function call which produced it, so in your case it would be accessed like $row['count(*)'].

like image 172
prodigitalson Avatar answered Mar 27 '23 07:03

prodigitalson


Try

select genre, count(*) AS total from movies group by genre

Use total as your count for eg.

echo $result['total'];
like image 23
Jenson M John Avatar answered Mar 27 '23 05:03

Jenson M John