I'm trying to count different columns in a single table and store them as variables in PHP, I don't think I should be doing it this way I don't think:

$dog_count = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM animals WHERE animal='dog'"));
$cat_count = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM animals WHERE animal='cat'"));
$parrot_count...

I'm thinking there is probably a better way to count statistics. Any advice?

Thanks :)

share|improve this question
Another question, say we had 10 million rows in the database, would it still be okay to COUNT() every minute? Would it be better to have a summary table? Thanks in advance – user1104791 Dec 19 '11 at 20:57

1 Answer

up vote 2 down vote accepted

You could get all the aminals and their respective counts in one query:

SELECT animal, COUNT(*) AS AnimalCount
    FROM animals
    GROUP BY animal
share|improve this answer
Aha, thank you very much, solved my problem :) – user1104791 Dec 19 '11 at 20:32
Sorry for the basic questions, how would I go about putting the count into a variable, $cat_count, $dog_count, etc? – user1104791 Dec 19 '11 at 20:41

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.