cbreuner cbreuner - 5 days ago 6
CSS Question

Styling table output from SQL into respective bootstrap columns

I'm using SQL and PHP to create a table filled with data in a simple html table. It all works fine but I am trying to include each item in its own div in a bootstrap 3 column layout. The issue here is this requires adding rows/columns in a non-repetitive order. Please see the jsfiddle to see the grid layout I am trying to achieve.

Using foreach I get the data to display nicely in a simple table. My question is what would be the best route make the output format like the jsfiddle? Any tips would be greatly appreciated! I am assuming I will need some JS to achieve this? Thank you for your time.

NOTE Make the Javascript tab thin to see the actual effect otherwise it wraps.
Layout I am looking for

<!-- CODE FOR TABLE LAYOUT -->
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
<h2>
Database Item 1
</h2>
<p>
Detials about this item
</p>
<p>
<a class="btn" href="#">View details »</a>
</p>
</div>
<div class="col-md-4">
<h2>
Database Item 2
</h2>
<p>
Detials about this item
</p>
<p>
<a class="btn" href="#">View details »</a>
</p>
</div>
<div class="col-md-4">
<h2>
Database Item 3
</h2>
<p>
Detials about this item
</p>
<p>
<a class="btn" href="#">View details »</a>
</p>
</div>
</div>
<div class="row">
<div class="col-md-4">
<h2>
Database Item 4
</h2>
<p>
Detials about this item
</p>
<p>
<a class="btn" href="#">View details »</a>
</p>
</div>
<div class="col-md-4">
<h2>
Database Item 5
</h2>
<p>
Detials about this item
</p>
<p>
<a class="btn" href="#">View details »</a>
</p>
</div>
<div class="col-md-4">
<h2>
Database Item 6
</h2>
<p>
Detials about this item
</p>
<p>
<a class="btn" href="#">View details »</a>
</p>
</div>
</div>
</div>

Answer

You don't need any javascript, you just need to iterate and close the row div according to number of iteration

echo '<div class="container-fluid">';
for($i=1; $i < count($array) + 1; $i++) {
     if(is_int(($i - 1) / 3) || ($i - 1) == 0) {
         echo '<div class="row">';
     }
     echo '<div class="col-md-4">';
     echo '<h2>'. $array[$i]['item_name'].'</h2>';
     echo '<p>'.$array[$i]['item_descrption'].'</p>';
     echo '<p><a class="btn" href="#">View details »</a></p>';
     echo '</div>';
     if(is_int($i/3) {
        echo '</div>';
     }
 }
 echo '</div>';
Comments