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:


