How to display a MySQL database record only once when duplicates exist in PHP?
Suppose my db looks like this:
id | person_id | hobby | time
-----------------------------------
1 | 67 | golf | mon
2 | 33 | reading | tues
3 | 67 | baseball | fri
4 | 67 | golf | sun
I want to display a list of all the hobbies of person with id 67 on a page.
If I do this:
$query = mysql_query("SELECT * FROM hobbies WHERE person_id = '67'");
while ($row = mysql_fetch_assoc($query)) {
echo $row['hobby'];
}
I wil get:
golf
baseball
golf
I want duplicate hobbies entered by the same person id to show only once, 开发者_C百科so it will show:
golf
baseball
And by duplicate I mean however many redundant times the same hobby by the same person is entered in a database (as long as it's more than once it should shown only once).
How can this be done?
$query = mysql_query("SELECT DISTINCT `hobby` FROM `hobbies` WHERE `person_id` = '67'");
DISTINCT
will not show duplicates for hobby
.
Documentation.
$query = mysql_query("SELECT * FROM hobbies WHERE person_id = '67' GROUP BY hobby");
while ($row = mysql_fetch_assoc($query)) {
echo $row['hobby'];
}
精彩评论