1

I have the following code which has worked perfectly up until now:

$db->table = "horse_products as p";
$db->colums = "p.*, l.address as address, l.storename as supplier_name, c.title as cat_title, c.id_parent as id_parent";
$db->join =    "LEFT JOIN locations as l ON l.id = p.id_location"
                ." LEFT JOIN categories as c ON c.id = p.id_category WHERE c.id_parent = 8";
$db->orderBy = "p.id_location ASC, p.id_product ASC";
$items = $db->Select();

Previously p.id_category was an integer because only one category within the 'categories' table was allowed to be associated with a product. However today I decided to make p.id_category a comma separated array. The downside to this is that when I try to echo $item['cat_title'], I only get the first c.title within the p.id_category array. I would like to get the title for all the categories within p.id_category. Can anyone help me here? I hope that I've made myself understood, as a MySQL novice even getting my LEFT JOIN's to work was a challenge :-)

EDIT:

Sat myself down this morning to find a solution and found it in the answer to the following question: MySQL: How to fetch data with left-join if column contains multiple ids?. Thanks to all that helped.

2 Answers 2

1

Bad idea beacause id_category should be unique integer value. If you want to have m:n relationship you need add another table with at least two primary foreign keys from tables that you want to have relationship. So in your case you will create table title_to_categories with primary key id_product and id_category. Id_product will be equals to p.id and id_category to c.id.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Filip. I am going to have to store these relationships in separate tables in the near future because my database is growing with ever more interrelationships. For now though I used GROUP_CONCAT() and FIND_IN_SET() which did the trick short term.
Ok for next time when your creating database in php thinking about model before you start using it. That will save you a lot of your time.
0

Try with:

$items= $db->fetchAll();

And then go with foreach.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.