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
$number_cols = 4;//Number of columns for large screens
$col_width = 12 / $number_cols;//12 column layout
$row_count = 0;//The loop counter
$select = $db->prepare("SELECT `item_name` FROM `products`");
$select->execute();
while ($row = $select->fetch(PDO::FETCH_ASSOC)) {
    if ($row_count == 0) {
        echo '<div class="row">';
    }
    echo "<div class='col-lg-$col_width col-md-$col_width col-sm-6 col-xs-12 a-col'>".$row['item_name']."</div>";
    if ($row_count == ($number_cols - 1)) {
        echo '</div>';
    }
    $row_count++;
    if ($row_count % $number_cols == 0) {
        echo '</div><div class="row">';
    }
}

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 lg
PHP MySQL loop Bootstrap Columns sm
PHP MySQL loop Bootstrap Columns sm
PHP MySQL loop Bootstrap Columns xs
PHP MySQL loop Bootstrap Columns xs