Jump to content

Mysql Fetch Array Unique


chibineku

Recommended Posts

I want to dynamically populate a list of product categories, each of which will link to a page with all that category's products on it. Each product in my database has a main category associated with it, so all I need to do is to fetch the category row and for each entry echo an appropriate link (and, for the product category nav menu, an appropriate li). Obviously there will be more than one product per category, so I want a unique array. Is there one single query for this, or should I just fetch the array normally and then do:$array = array_unique($mysql_fetch_array);?My queries so far have all been extremely basic, and I am trying to learn the little nuances that save lines and save time. I already have a complicated document for inserting/updating my shopping basket and THEN learned about ON DUPLICATE KEY UPDATE - what a time saver that would've been.

Link to comment
Share on other sites

I'm confused about what you mean by a unique array. You'll have an array for categories, and for each category an array of products, right? Assuming you're just getting all of the products in a category from the database there shouldn't be any duplicate records, it should list each product in the category exactly once.

Link to comment
Share on other sites

Sorry - I mean that I want to get a list of all the possible categories, and use that to create a sort of index page. So instead of knowing every category I have, if I want to create a new category, I just need to create database entries with category X and my index page/nav menu will automatically reflect the new category.

Link to comment
Share on other sites

If you're looking for a way to just list your categories, you can just select them from the database and loop through the result set to list each one, you don't necessarily need to store them all in an array first. e.g.:

$result = mysql_query('SELECT id, title FROM categories');while ($row = mysql_fetch_assoc($result)){  echo '<li><a href="categories.php?id=' . $row['id'] . '">' . $row['title'] . '</a></li>';}

If you don't have a category table, if your categories are just titles or something in your products table, you can use the DISTINCT keyword to get the distinct values. e.g.:SELECT DISTINCT category FROM products

Link to comment
Share on other sites

SELECT DISTINCT category FROM products
Ah, that's the nugget of nougat I needed - arigato!
Link to comment
Share on other sites

Archived

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

×
×
  • Create New...