What I'm trying to accomplish is to count the number of entries in a sql db across 5 columns and return the 5 entries that have the most occurrences. Basically create a TOP 5 list.
A simple example of what I want to do would be to find out the two most favorite fruit out of a group of people. I ask them to list their three most favorite fruits. They input that data into a form and it ends up in a sql database looking like this:
ID name fruit1 fruit2 fruit3 fruit4 fruit5
1 bob apples grapes bananas strawberries melons
2 sam grapes mangos apples blueberries cherries
3 amy melons apples grapes oranges grapefruit
4 jon apples bananas oranges pinapple strawberries
I want to calculate which fruit in all five columns has the most number of occurrences, to where my output is the following:
The most popular fruits are apples(4) and grapes(3).
Here is some code that I cobbled together which will list the occurrences of the fruit in the fruit1 column. But I'm not sure how to:
- expand that to count 5 columns worth of entires.
- only return the top 5 occurrences.
- or deal with the event that some entries may have the same number occurrences, which may make the top 5 list grow to 6 or 7 entries.
$query = "SELECT *, COUNT(id) FROM fruits GROUP BY fruit1";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo $row['fruit1'] . "(". $row['COUNT(id)'] . ")";
echo "<br />";
}
Any help you can give would be greatly appreciated.