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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.