PHP Three column tables from a product database

Just wondering if anyone can give me a hand with sassy php for every loop ...

I currently have a table of products that I selected for the table, each with 75% hr> then, but I would like it to become a table with three columns. I do not mind if, for example, in the product table there are 4 products, and in the first column and in the next 2 - empty, etc.

Current code as below ...

<?php if($results && mysql_num_rows($results) > 0){ ?> <?php $i = 1; while($row = mysql_fetch_assoc($results)){ $i++; ?><table width="750"> <tr> <td id="topbottom" width="220px"><a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/<?php echo($row['imageName']); ?>" width="220px"/></a></td> <td id="pad"> <h1><?php echo($row['productName']); ?></h1> <br> <h2><?php echo($row['productType']); ?></h2> <br> <h3> &pound;<?php echo($row['productPrice']); ?></h3> <br> <?php echo($row['productDesc']); ?> <br /><br /> <a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/findout.png"/></a> </td> </tr></table><hr color="#6c3600" width="75%" /> <?php } ?> <?php } else { echo("<p>No items found</p>"); } ?> 
+4
source share
1 answer
 <table width="750"> <?php if($results && mysql_num_rows($results) > 0){ ?> <?php $i = 0; // Set this to 0, since php is 0 based $cols = 3; // Number of cols you want while($row = mysql_fetch_assoc($results)){ // Use the modulus operator to see if i is an even multiple of $cols // If it is then we need to open a new table row if($i % $cols == 0) { echo '<tr>'; } ?> <td id="topbottom" width="220px"><a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/<?php echo($row['imageName']); ?>" width="220px"/></a></td> <td id="pad"> <h1><?php echo($row['productName']); ?></h1> <br> <h2><?php echo($row['productType']); ?></h2> <br> <h3> &pound;<?php echo($row['productPrice']); ?></h3> <br> <?php echo($row['productDesc']); ?> <br /><br /> <a href="products.php?id=<?php echo($row['productId']); ?>"/><img src="images/findout.png"/></a> </td> <?php $i++; // Same as above but we want to close the table row after $cols if($i % $cols == 0) { echo '</tr>'; } ?> <?php } ?> </table><hr color="#6c3600" width="75%" /> <?php } else { echo("<p>No items found</p>"); } ?> 

Key things to look for:

Set $i to 0 since php uses 0-based arrays

Set up a variable called $cols that makes it easy to change the number of columns

The % (module) operator is used to determine if the number is an even number of columns to dynamically add <tr> tags to the right places.

+2
source

All Articles