Re: mysql record display in table format
| From: | Robin Vickery | Date: | Thu, 20 Jul 2000 08:26:47 +0000 |
| Subject: | Re: mysql record display in table format | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-7381@lists.php.net to get a copy of this message | ||
Thomas Edison Jr. writes:
> HI,
>
> i'm working on a code to display records from mysql in
> a table format with 2 records side-by-side at a time.
> ie. that records number 1 and 2 in the first row of
> our HTML table and 3 and 4 in the next row and so
> on...
>
> how can this be possible? Whatever we try, either we
> get all the records in the same row or each in a
> different row. How can we divide it to get 2 records
> in each row?
There's several ways to do it, the easiest and least flexible and
maintainable is just to hardcode the columns in like this:
<table>
<?php
$result = mysql_query($query, $connection);
while ( $row = mysql_fetch_array($result) )
{
print "<tr>\n";
print "<td> $row[fieldName] </td>\n";
if ($row = mysql_fetch_array($result))
{
print "<td> $row[fieldName] </td>\n";
}
else
{
print "<td> </td>\n";
}
print "</tr>\n";
}
?>
</table>
Alternatively you could loop through the result and then pad out
the last row:
<table border=1>
<?php
$numcols = 2;
$col = 0;
$result = mysql_query($query, $connection);
while ( $row = mysql_fetch_array($result) )
{
if (!$col) { print "<tr>\n"; }
print "<td> $row[fieldName] </td> ";
if (!($col = ++$col % $numcols)) { print "\n</tr>"; }
}
if ($col)
{
while ($col % $numcols) { print "<td> </td>\n"; $col++; }
print "</tr>";
}
?>
</table>
Or you could loop through the columns of the table and if you run
out of results to print, pad out the rest of the row:
<table>
<?php
$numcols = 2;
$notfinished = 1;
$result = mysql_query($query, $connection);
while ($notfinished)
{
print "<tr>\n";
for ($col = 0; $col < $numcols; $col++)
{
if ( $row = mysql_fetch_array($result) )
{
print "<td> $row[fieldName] </td>\n";
}
else
{
$notfinished = 0;
print "<td> </td>\n";
}
}
print "</tr>\n";
}
?>
</table>
Hope this helps.
-robin
--
Robin Vickery...............................................
Planet-Three, 3A West Point, Warple Way, London, W3 0RG, UK
Email: robin@planet-three.net Phone: +44 (0)794 670 6395