Forum Moderators: coopster
I'm having trouble sorting my MySQL results in php.
Here's the database I have
id¦ value ¦ some info
--------------------------
1 ¦ name1 ¦ info
2 ¦ name1 ¦ info
3 ¦ name2 ¦ info
4 ¦ name2 ¦ info
5 ¦ name2 ¦ info
6 ¦ name3 ¦ info
What I'm trying to do, is to get a result in PHP looking like this:
name1 - 2results
name2 - 3results
name3 - 1result
the idea is for the script to show what values there are in the 'value' column, and show how many are there.
I made this working fine by searching for the exact value and then counting them, but the issue is that the there will be hundreds of different value.
thanks in advance :)
No, that would retrieve the data from the table however it will not group by the name value. To do this, you would have to use GROUP BY, as coopster has suggested. An example query using GROUP BY would be as follows:
$query = "SELECT * FROM `table_name` GROUP BY `value` ORDER BY `id` DESC";
SELECT
value,
COUNT(value) AS count
FROM table
GROUP BY value
ORDER BY value
;
just one more thing.. the values in the table are a list of lets say fruit, I need them to be sorted and shown by the first letter of the word. sort of like WikiPedia style listing, so for example this is what it would look like:
A:
Apple - 2C:
Cherry - 4
Cranberry - 1
M:
Mango - 5
Melon - 3
Mandarin - 3
$fruits = array('apple','cherry','cranberry','mango','melon','manderin');
$last = '';
foreach($fruits as $fruit) {
if($last != $fruit[0]) {
echo '<h3>'.$fruit[0].'</h3>';
$last = $fruit[0];
}
echo $fruit.'<br/>';
}
This should at least give you the right idea so that you can implement your own. :)
$query = "SELECT value, COUNT(value) AS count FROM table GROUP BY value ORDER BY value";
$result = mysql_query($query) or die mysql_error());
$last = '';
while($row = mysql_fetch_assoc($result)) {
if($last != $row['value'][0]) {
echo '<h3>'.$row['value'][0].'</h3>';
$last = $row['value'][0];
}
echo $row['value'].'<br/>';
}