Reputation: 41
Just wondering if someone could give me a hand with a cheeky php for each loop...
I currently have a table of products which i have echo'd out to a table each with a 75% < hr > afterwards but i'd like it to become a Three column table. I don't mind if for example there are 4 products in the table of products and its in the first column and the next 2 are 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> £<?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>");
}
?>
Upvotes: 4
Views: 1823
Reputation: 7086
<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> £<?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 var called $cols
which allows you to change the number of columns easily
Used the %
(modulus) operator to find if a number is an even multiple of columns to dynamically add the <tr>
tags in the correct places.
Upvotes: 2