Jump to content

Recommended Posts

Hey everyone,

 

I've recently put together a quick store script for a friend using the tutorial over at http://www.phpwebcommerce.com/

 

My question:

Does anyone know how I would make it so each product could be added to multiple categories (example: place the same TV inside "Electronics" and "Televisions" without having to add a second instance of the item?

 

I'm stumped, as I've never actually run into code/scripting that does this. Any help would be amazing.

 

Thanks,

According to that tutorial you have a category table (to describe the categories) and a product table which includes a field to specify the category id. SO, you are left with a 1-to-1 relationship where a product can be assigned to one, and only one, category. But, you want a one to many relationship.

 

The solution is to create an intermediary table (e.g. prod_cat) and remove the category id field from the product table. The new table would only need two fields: the category id and the product id. You can then associate a product to as many categories as you wish. Howevever, you will have to review all your existing queries that pull data from the product table and modify them as needed to JOIN the new table.

Here's an example of what an existing query might look like and how it would be modified:

 

Example existing query to get details for a single product (including the category)

SELECT * FROM products
JOIN category on products.cat_id = categories.cat_id
WHERE prod_id = '$id'

 

New query where categories are in an associative table

SELECT * FROM products
JOIN prod_cat ON products.prod_id = prod_cat.prod_id
JOIN categories ON prod_cat.cat_id = categories.cat_id
WHERE prod_id = '$id'

Note this will return multiple records based upon how many categories the product is associated with. Use the first record to get the product details and all the records to get all the category names

  • 3 months later...
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.