Jump to content

unique mysql values


brad_langdon

Recommended Posts

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

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.