0

I have 2 tables. product_data contains all the details about the product and product_images which has all the images for each product. I joined both the tables but the problem is that some products have more than 2 images. so the product rows duplicate

product_name  | description | ucode |  star_rating | product_image

cheese            packed       321        3            1.jpg
cheese            packed       321        3            1.jpg
cheese            packed       321        3            3.jpg
meat              canned       F98        1            meat1.jpg
milk              canned       G43        5            milk1.jpg
milk              canned       G43        5            milk2.jpg
milk              canned       G43        5            milk3.jpg
milk              canned       G43        5            milk4.jpg

When I have a foreach loop

 foreach ($products as $product):
    //display the product details once and all the images for that product
    endforeach;

The output will be like,

product 1          1.jpg
                   2.jpg
                   3.jpg
product 2          meat1.jpg
product 3          milk1.jpg
                   milk2.jpg
                   milk3.jpg
                   milk4.jpg

I want to list all the products along with the images. How can I display the product details only 1 time and all the images for that product and move to the next product? There's is a maximum of 6 images for a product

The SQL query - 3 tables have been joined

SELECT *
FROM product_data p
LEFT JOIN product_img_map im ON im.product_id = p.product_id
LEFT JOIN product_images i ON i.photo_id = im.photo_id
2
  • Can you show us the SQL query? Commented Mar 22, 2013 at 17:01
  • @HydraIO i have added the sql code.. Commented Mar 22, 2013 at 17:23

2 Answers 2

1

You can put it all in an array:

foreach ($products as $product) {
    ....
    $product_array[$product_name]['images'][] = $product_image;
    ....
}

then you will have more control over your output by looping through the product array you created.

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

Comments

0

You can use GROUP_CONCAT:

SELECT `product_data`.*,
GROUP_CONCAT(`product_data`.`product_image`) as Pictures
FROM `product_data`
GROUP BY `product_data`.`product_name`

You will get a new row Pictures containing all images separated by comma.

1 Comment

actually there 3 tables joined basically 1 table is used to map the product id with image id. i have added the sql code. Is it possible to use the concat with my sql code?

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.