phpmysqlfetchbackendgrid-system

How to echo a specific content after fetching 4 rows in MySQL database


I am making a backend system, and the displayed product from the index page should follow the grid system. For example, I have 8 products from MySql database. I want to divide them into 2 rows, 4 products each. So my PHP code would look like:

<div class="row">
<?php
$result = mysqli_query($conn, "SELECT * FROM products");
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-dsk-4"><?php echo $row["name"]; ?></div>
<?php
}
?>
</div>

As you can see in the code, I want after echoing 4 times (4 times <div class="col-dsk-4">), the while loop exits, then continues a new <div class="row"> until it loops through all the element in the MySql Table.

Is my solution correct or not? If so, please help me, else, please show me your solution.


Solution

  • You can try the code below.

    What I'm doing is instead of using while I've switched it to a foreach to go through the array.

    I'm using count to dictate when the <div class="row"> should be added. On the first item and every 4th item, it should add a new row.

    I've also updated the way I'm calling <?php ?> so it's easier/cleaner to read.

    If you have any questions let me know:

    <?php $result = mysqli_query($conn, "SELECT * FROM products"); ?>
    <?php $rows = mysqli_fetch_array($result); ?>
    
    <!-- Use count to decide when to put a new div with class 'row' -->
    <?php $count = 1; ?>
    
    <?php foreach ($rows as $key => $row) { ?>
    
        <!-- Create a new div with class 'row' on the first item + everytime theres a 4th one -->
        <?php if ($count == 1 || ($count % 4 == 0)) { ?>
            <div class="row">
        <?php } ?>
    
            <div class="col-dsk-4">
                <?php echo $row["name"]; ?>    
            </div>
    
        <!-- Close div with class 'row' everytime theres a 4th one -->
        <?php if ($count == 1 || ($count % 4 == 0)) { ?>
            </div>
        <?php } ?>
    
        <!-- Increment the count -->
        <?php $count++; ?>
    <?php } ?>