简体   繁体   English

从Mysql PHP显示产品

[英]Displaying Products from Mysql PHP

RDBMS: MySQL 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. 假设有100个产品,每个产品都有1-3张图片。

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. 第二个查询:基于ProductID获取图像。 If you wanna do something fancy, you can use java script to rotate the images. 如果您想做一些花哨的事情,可以使用Java脚本旋转图像。

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. 您可以使用group_concat() Mysql函数group_concat()获取所有图像,而无需复制记录。 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. 您将获得带有逗号分隔图像的产品的结果,然后在PHP中分解这些逗号分隔图像并将其显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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