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. Quote Link to comment 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? Quote Link to comment 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 Quote Link to comment 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. Quote Link to comment 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 Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.