简体   繁体   中英

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. 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. 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:

$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:

<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.

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

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