Omnipresent Omnipresent - 2 months ago 24
Perl Question

How can I display data in table with Perl?

I am getting data from a database. It has 4 rows and 6 columns. I want to show this in an HTML table but am having problems. I've made the TH for the 6 columns. However, I am having problems in displaying the 4 rows. This is what I have so far:

while (($f1, $t2, $n3, $k4, $d5, $e6) = $sth1->fetchrow_array)
{
push (@first, $f1);
push (@second, $t2);
push (@third, $n3);
push (@fourth, $k4);
push (@fifth, $d5);
push (@sixth, $e6);
}


@first, @second...and others are arrays

While dsplaying data if I do:

foreach (@first)
{
print "<td>$_</td>";
}


That is displaying data vertically but I want it to display horizontally.

Answer

The code in the question is written using Perl's DBI (DataBase Interface):

print "<table>\n";
while (($f1, $t2, $n3, $k4, $d5, $e6) = $sth1->fetchrow_array)
{
    print "  <tr>\n";
    print "    <td>$f1</td>\n";
    print "    <td>$t2</td>\n";
    print "    <td>$n3</td>\n";
    print "    <td>$k4</td>\n";
    print "    <td>$d5</td>\n";
    print "    <td>$e6</td>\n";
    print " </tr>\n";
}
print "</table>\n";

Or you could read the row into an array and then print the array more succinctly:

print "<table>\n";
while (my(@row) = $sth1->fetchrow_array)
{
    print "  <tr>\n";
    print "    <td>$val</td>\n" foreach my $val (@row);
    print " </tr>\n";
}
print "</table>\n";