简体   繁体   中英

Displaying Products from Mysql PHP

RDBMS: MySQL

I'm designing an online store and need some assistance in displaying the products for a category page. Say there are 100 products and each product has 1-3 images.

I need to display all products, but also multiple images per product. I'm having trouble in finding a way to display it correctly.

Database schema:

在此处输入图片说明

I can retrieve the data as an array and loop through it but if I join the tables with all of the images I'm going to have duplicate rows retrieved with different images in each. I'm having trouble understanding how I would display multiple images for every product when viewing all products.

Let me know if you'd like me to elaborate further. Thanks in advance!

Write two separate queries to fetch data from the database:-

  1. Fetch all the products from the database and then display them to the page
  2. Second query: Fetch the images based on ProductID. If you wanna do something fancy, you can use java script to rotate the images.

Let me know if you need further assistance. Thank you!

You can use group_concat() Mysql function to get all the images in one go, without duplicating the records. Below example shows the same.

select p.product_id, p.product_name, group_concat(pi.image_path)
from procuct p join product_images pi on p.product_id = pi.product_id
group by p.product_id, p.product_name

This will give you all the paths as comma separated list along with each product record.

Use this query:

select products.*,GROUP_CONCAT(image_path) 
form products 
LEFT JOIN product_images on products.product_id = product_images.product_id
GROUP BY product_images.product_id

You will get the result of products with comma separated images then explode those comma separated images in PHP and display it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM