简体   繁体   中英

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

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!

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(*)'] .

Try

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

Use total as your count for eg.

echo $result['total'];

Try this,

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

Now you can access like $result['total_genre_movies']

It's easier if you alias the result of count(*)

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

Then you can access it as $row['total'] when you fetch the result into $row in exactly the same way you'd reference $row['genre']

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

现在您可以访问$ result ['genre_count']

Try this,

$result = mysql_query("select genre, count(*) as genre_count from movies group by genre");

while($row = mysql_fetch_array($result)) {

   $genre       = $row['genre'];
   $genre_count = $row['genre_count'];

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM