Randell Farrugia Randell Farrugia - 2 months ago 18
PHP Question

HTML table grid in PHP

I am currently doing some basic PHP and I am getting products from mysql and displaying each product with the corresponding details in a table.

Currently they are one underneath each other

Product1 Name
Product1 Price
Product1 Description

Product2 Name
Product2 Price
Product2 Description


Now I want to display them in a grid of 3 columns.
which means displaying 3 products side by side, then the 4th product is displayed underneath the 1st product and so on.

$displayAllProducts.=
"
<tr><td>Product Name : </td><td>$productName</td></tr>
<tr><td>Product Price : </td><td>$productPrice</td></tr>
<tr><td>Product Qty : </td><td>$productQty</td></tr>
<tr><td colspan =\"2\"><img src=\"$imagePath\" width = \"100\" height = \"100\"></td><td></td></tr>
<tr><td colspan =\"2\"><a href=\"singleProduct.php?pid=$productID&uid=$uid\">View Product<br/><br/><br/></td><td></td></tr>
";



<table>
<?php
echo $displayAllProducts;
?>
</table>

Answer

Without seeing your actual code that loops through your db rows, here is a general idea. This will make each $displayAllProducts its own table, nested in the main table <td>'s

$i=1;  // start a general counter
while($i<$number_of_db_rows){
if($i%3 = 1) {   // If number is 1,4,7,etc start a new row
$displayAllProducts.= "<tr>"; 
}
$displayAllProducts.=
    "
        <td>     // put each db row inside a cell
        <table>  // create a bounding table
        <tr><td>Product Name : </td><td>$productName</td></tr>
        <tr><td>Product Price : </td><td>$productPrice</td></tr>
        <tr><td>Product Qty  : </td><td>$productQty</td></tr>
        <tr><td colspan =\"2\"><img src=\"$imagePath\" width = \"100\" height = \"100\"></td><td></td></tr>
        <tr><td colspan =\"2\"><a href=\"singleProduct.php?pid=$productID&uid=$uid\">View Product<br/><br/><br/></td><td></td></tr>
        </table> 
        </td>  
     ";
if($i%3 = 0) {   // If number is 3,6,9,etc close the row
$displayAllProducts.= "</tr>";
}
$i++ // increase the counter to start again
}  // ends the loop


<table>
<?php
echo $displayAllProducts;
?>
</table>
Comments