Development

PHP MySQL loop with Bootstrap 4 columns

Here is how to implement the Bootstrap grid system into a PHP MySQL foreach loop.

The code is set to be 4 columns on large screens, 2 on small screens and just the 1 on mobile.

The code loops through all the returned rows as expected, counting each row and putting the value inside the column class however using a modulo to determine if we need to close the row and start a new one.

Columns and rows in a loop

This is dependent on $number_cols which is set at 4. Therefor when $row_count divided by $number_cols = 0 it closes the row and starts a new one. You can see this in continuous action with 4%4=0, 8%4=0, 12%4=0 so forth.

<?php
$width_xsml = 12;//Columns size for extra small screen
$width_sml = 6;
$width_med = 4;
$width_large = 3;//Column size for large screen

$col_width = 12 / $width_large;//12 column layout
$row_count = 0;//The loop counter

$select = $db->prepare("SELECT `item_name` FROM `products` WHERE `is_aval` = 1;");
$select->execute();

while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
    if ($count % $width_large == 0) {
        echo '<div class="row">';
    }
    $count++;
    echo "<div class='col-$width_xsml col-sm-$width_sml col-md-$width_med col-lg-$width_large'>";
    echo $row['item_name'];
    echo '</div>';
    if ($count % $width_large == 0) {
        echo '</div>';
    }
}

You can get the full code with some CSS in this Gist.

With some CSS to have emphasis on the rows and columns this is what it looks like when I did a loop on the 2019 Cricket Worldcup fixture:

PHP MySQL loop Bootstrap Columns lg
PHP MySQL loop Bootstrap Columns sm
PHP MySQL loop Bootstrap Columns xs
Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago