I am tring to display all my products within their category, so something like:
Category Name1
Product Name1, Product Name2 …
Category Name2
Product Name3, Product Name4 …
I am using oscommerce, So the database structure is not my choice. The database tables I need to use are
products_to_categories: holds the products_id and categories_id
products_description:holds products_id and products_name (other info in this table are not important)
category_description: holds the categories_id and categories_name
I have tried everything and i only can get to echo the products (all together) and categories all together, but I can’t get them in a way that all the products within a category sit under the specified name
As I said everything I tried resulted in a way that simply echoed all the categories AND THEN all the products
I really hope you can help
thanks
3
Answers
You’ll likely need a
LEFT JOIN
in your SQL, to merge the three tables together, and order the query bycategory_name, product_name
.Something like:
Then your PHP to output the list would be something like:
I dont understand fully how you want to display. I hope you like to display like this
Easiest way i think, get distinct list of category in an array.
with cat id and cat name
Loop that array and print products for each Category.
If category list is huge storing it in array and looping will be a bad idea.
There are two ways of approaching this, and the idea behind is was already given as an answer here, by Zod.
The first way is using category_description to get all categories (whether it’s full of products or not), the second way is to only extract categories that are used (i.e., not getting a complete list of categories). I’ll go through the first way; getting all categories.
Run through category_description, and get the IDs and category names into an Array.
Now, run through that array with
foreach
and grab all product_ids from products_to_categories. (SELECT products_id FROM products_to_categories WHERE categories_id=[CATEGORY ID GOES HERE]
).Now that you have your product IDs that are associated with the concurrent category, you can run through the products_description and get their name. Essentially, your code should look like: