brad_langdon Posted June 7, 2009 Share Posted June 7, 2009 Hi, I have a data base full of products. One of the fields in the database is labeled "category". I want to list each category. The problem is that I have many products in the same category so I need to list each category only once. This is what I have at present... $result = mysql_query("SELECT * FROM products") or die(mysql_error()); while($row = mysql_fetch_array($result)) { echo $row['category']; } Obviously this lists the duplicates as well. I read a tutorial on the 'DISTINCT' function. I tried it with no success. The tutorials I read did not explain how to use it in a query such as I have above. If anyone can explain to me how to use it properly or maybe an alternative that would be much appreciated. I hope I have posted this in the right section :-\ Thanks in advance guys. Link to comment https://forums.phpfreaks.com/topic/161228-unique-mysql-values/ Share on other sites More sharing options...
Ken2k7 Posted June 7, 2009 Share Posted June 7, 2009 Can you post the trial you did with DISTINCT? Link to comment https://forums.phpfreaks.com/topic/161228-unique-mysql-values/#findComment-850774 Share on other sites More sharing options...
alco19357 Posted June 7, 2009 Share Posted June 7, 2009 if each product has a unique product id, then do this (assume product id is equal to = 'pid' in db) $result = mysql_query("SELECT * FROM products")or die(mysql_error()); $save_buffer = array(); while($row = mysql_fetch_array($result)){ if(!in_array($row['pid'], $save_buffer)){ echo $row['category']; $save_buffer[] = $row['pid']; } } #this will be a simple hack to avoid multiple category listing... best practice is to separate your categories and products into separate tables Link to comment https://forums.phpfreaks.com/topic/161228-unique-mysql-values/#findComment-850867 Share on other sites More sharing options...
Ken2k7 Posted June 7, 2009 Share Posted June 7, 2009 With SQL, I think distinct would work. Even group by will work. SELECT DISTINCT category FROM products; SELECT category FROM products GROUP BY category; Both should do the same thing. Link to comment https://forums.phpfreaks.com/topic/161228-unique-mysql-values/#findComment-850870 Share on other sites More sharing options...
brad_langdon Posted June 7, 2009 Author Share Posted June 7, 2009 Thanks guys group by worked a charm Link to comment https://forums.phpfreaks.com/topic/161228-unique-mysql-values/#findComment-850904 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.