Currently I am searching a database for carpets and I can list them each on their own row but am not sure how to list them in 3 columns. Here is my code: include('connect.php'); $result = mysql_query("SELECT * FROM standarddecor WHERE decortype = 'Carpet' && standard='yes'"); while($row = mysql_fetch_array($result)) { echo "<tr><td><img src=\"standarddecor/" . $row['imgname'] . "\" alt=\"" . $row['decorname'] . "\"><br />" . $row['decorname'] . "</td></tr>"; } Code (markup): Any help would be greatly appriciated. Thank you in advance
should work: include('connect.php'); $result = mysql_query("SELECT * FROM standarddecor WHERE decortype = 'Carpet' && standard='yes'"); $i = 1; while($row = mysql_fetch_array($result)) { if($i == 1) { echo "<tr>"; } echo "<td><img src=\"standarddecor/" . $row['imgname'] . "\" alt=\"" . $row['decorname'] . "\"><br />" . $row['decorname'] . "</td>"; if($i == 3) { echo "</tr>"; $i = 0; } $i++; } PHP:
you should add a small peice after the while loop to check if the last row is closed, if for example we have 5 rows, the last row will not terminate. after the while loop add: if($i < 3) echo "</tr>"; PHP:
You need to use the modulus operator. The above example will only work if you have 3 rows total. $result = mysql_query("SELECT * FROM standarddecor WHERE decortype = 'Carpet' && standard='yes'"); $total_rows = mysql_num_rows($result); $count = 1; while($row = mysql_fetch_array($result)) { if($count==1 || $count%3=1) { echo '<tr>'; } echo "<td><img src=\"standarddecor/" . $row['imgname'] . "\" alt=\"" . $row['decorname'] . "\"><br />" . $row['decorname'] . "</td>"; if($count == $total_rows || $count%3 == 0) { echo '</tr>'; } $count++; } PHP:
Note: i used the statement: if($i < 3)echo "</tr>"; becuase they are resetting the $i to 0 everytime. it will also work for more than 3 rows.