[英]How to display all categories for all products in MySQL and PHP?
I'm a beginner in MySQL and PHP and I need your help to get to know the solution. 我是MySQL和PHP的初学者,需要您的帮助来了解解决方案。 I would like to display a list of products and related categories.
我想显示产品和相关类别的列表。 Products and categories are in the many-to-many relationship.
产品和类别之间存在多对多关系。 Google solutions are very confusing to me.
Google解决方案令我感到困惑。 I will be very grateful for any advice.
如有任何建议,我将不胜感激。
My code displays duplicate products. 我的代码显示重复的产品。 Duplicated as many times as the category has.
与类别重复了多次。 Eg:
例如:
Product1 - Category1;
Product1 - Category2;
Product1 - Category3;
Product2 - Category1;
Product3 - Category3;
index.php: index.php文件:
$result = $pdo -> query('
SELECT product.id,
product.name AS product_name,
seller.name AS seller_name,
category.name AS category_name
FROM product
LEFT JOIN seller ON product.sellerid = seller.id
LEFT JOIN product_category ON product.id = product_category.productid
LEFT JOIN category ON product_category.categoryid = category.id
');
foreach($result as $row)
{
$products[] = array(
'id' => $row['id'],
'product_name' => $row['product_name'],
'seller_name' => $row['seller_name'],
'category_name' => $row['category_name']
);
}
index.html.php: index.html.php:
<ul>
<?php foreach($products as $product): ?>
<li>
<span><?php htmlout($product['id']); ?></span>
<span><?php htmlout($product['product_name']); ?></span>
<span><?php htmlout($product['seller_name']); ?></span>
<ul>
<li>
<span><?php htmlout($product['category_name']); ?></span>
</li>
</ul>
</li>
<?php endforeach; ?>
</ul>
How to display all categories for each product? 如何显示每个产品的所有类别? What should the loops look like?
循环应该是什么样? I would like to achieve:
我想实现:
Product1 - Category1, Category2, Category3;
Product2 - Category1;
Product3 - Category3;
You can use GROUP_CONCAT()
to get all the sellers and categories in each row. 您可以使用
GROUP_CONCAT()
获取每一行中的所有卖方和类别。
SELECT product.id, product.name,
GROUP_CONCAT(DISTINCT seller.name) AS sellers,
GROUP_CONCAT(DISTINCT category.name) AS categories
FROM product
LEFT
JOIN seller
ON product.sellerid = seller.id
LEFT
JOIN product_category
ON product.id = product_category.productid
LEFT
JOIN category
ON product_category.categoryid = category.id
GROUP BY product.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.