in reply to How can I display an entire MySQL table in Perl?

There are a few ways to display an entire table. The idea is to iterate through the rows that are returned (a list), where each row contains a numbers of elements (another list).
# prepare the SQL my $sth = $dbh->prepare('select * from table'); # execute $sth->execute(); # fetch first row my @row = $sth->fetchrow_array(); # print remaining rows while (my @row = $sth->fetch_array()) { print join(',', @row), "\n"; }
Here is a different way that uses my favorite DBI method, selectall_arrayref():
my $res = $dbh->selectall_arrayref('select * from table'); foreach my $row (@$res) { print join(',', @$row), "\n"; } # html-table style print "<table>\n"; foreach my $row (@$res) { print "\t<tr>\n"; print map { "\t\t<td>$_</td>\n" } @$row; print "\t</tr>\n"; } print "</table>\n";
If you find yourself doing a lot of the last example, check out DBIx::XHTML_Table, but HTML::Template is still the better choice. Be sure and read HTML::Template Tutorial (which i _finally_ updated to make 'Y2K+2' compliant) for info on displaying database results with it.

UPDATE:
Trimbach++ for reminding what i have so long forgotten.

Just to keep up with ease, here is how it's done in DBIx::XHTML_Table:

use DBIx::XHTML_Table; my $table = DBIx::XHTML_Table->new( 'DBI:mysql:database:host', 'user', 'pass') ) || die; $table->exec_query('select * from table'); print $table->output();
And that includes adding the names of the database columns wrapped in <th> tags. You can also stack the method calls:
print DBIx::XHTML_Table ->new('DBI:mysql:database:host', 'user', 'pass') ->exec_query('select * from table') ->output();
Of course, if that's all that DBIx::XHTML_Table did, then i would argue that a better way would be to wrap the CGI way into a subroutine ... but, it does more ... ;)

jeffa

L-LL-L--L-LL-L--L-LL-L--
-R--R-RR-R--R-RR-R--R-RR
F--F--F--F--F--F--F--F--
(the triplet paradiddle)

Replies are listed 'Best First'.
Re: Re: How can I display an entire MySQL table in Perl?
by Trimbach (Curate) on Jan 02, 2002 at 04:07 UTC
    If all you want to do is dump the contents of a SELECT statement to an HTML table, use the Power of the CGI module. Instead of this (from jeffa):
    # html-table style print "<table>\n"; foreach my $row (@$res) { print "\t<tr>\n"; print map { "\t\t<td>$_</td>\n" } @$row; print "\t</tr>\n"; } print "</table>\n";
    I would do this:
    use CGI qw(:standard *table); use CGI::Pretty; # For pretty-printed HTML print start_table; print Tr(td($_)) foreach @$rows; print end_table;
    Yes, it's just that easy. Of course, the more general solution is using some sort of templating scheme, but in general this is a pretty sweet way of outputting dynamic table data on the fly.

    Gary Blackburn
    Trained Killer