Search code examples
phpwebshop

Div-container around product-cards in php


I'm really new to php and now I got stucked on what I thought was something really easy. Byt I can't see wheres my problem is.

I'm trying to create a webshop page that displays all my products. To the problem! Here is my code so far. It displays all products as expected but it closes the main and product-container before all product-cards except from the first one. How to wrap all product-cards in the same div?

$pdo = connect();
$limit = 20;
$offset = 0;
$stmt = get_all_products($pdo, $limit, $offset);

$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

    <main>
        <section class="product-container">
        <?php
    foreach($rows as $row) {
        ?>
        <div class="product-card">
            <img class="product-image" src="<?php echo $row['Img'];?>" >
            <h2 class="title"><?php echo $row['ProductName']; ?></h2>
            <span class="price"><?php echo $row['Price'];?></span><span>:-</span>
        </div>
        </section>
    </main>
    <?php

}?> 

Solution

  • You should move the closing main and section tag after the foreach loop is closed.

    <main>
        <section class="product-container">
        <?php
        foreach($rows as $row) {
            ?>
            <div class="product-card">
                <img class="product-image" src="<?php echo $row['Img'];?>" >
                <h2 class="title"><?php echo $row['ProductName']; ?></h2>
                <span class="price"><?php echo $row['Price'];?></span><span>:-</span>
            </div>
        <?php }?> <!-- Close the foreach loop here -->
        </section>
    </main>