Entry
How do you print 2 HTML table columns from 1 select statement?
Jan 29th, 2004 16:10
Philip Olson, Jay Staton, php-general@lists.php.net
The following should print field 'name' in two rows.
<table>
<tr>
<?php
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
echo "\t<td>". $row['name'] ."</td>\n";
if ($i++ % 2) {
echo "</tr>\n<tr>\n";
}
}
?>
</tr>
</table>
To read about some PHP related discussion on the modulus operator (%),
check out this related faqt :
http://www.faqts.com/knowledge_base/view.phtml/aid/783/
Modulus works nicely for this. Also consider using a bitwise operator
as it's actually "faster."
if ($i & 1) {
echo "</tr>\n<tr>\n";
}
Read a little about bitwise operators here :
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/bitwise.html
http://marc.theaimsgroup.com/?l=php-general&s=bitwise
And of course the PHP manual is useful (check user comments too)
http://www.php.net/manual/language.operators.php
On a related note, let's say you wanted three rows instead of two, then
you might do something like:
<table>
<tr>
<?php
$i = 1;
while ($row = mysql_fetch_assoc($result)) {
echo "\t<td>". $row['name'] ."</td>\n";
if (($i++ % 3) == false) {
echo "</tr>\n<tr>\n";
}
}
?>
</tr>
</table>
And to visualize how this will be seen, something like so:
1 | 2 | 3
4 | 5 | 6
7 | 8 | 9
( keywords: modulas, modulus, alternating, columns, two, three )