5% assure discount from here only

Sunday, February 20, 2011

(21) Create a HTML Table based on the result of a database query.

Solution :

This type of requirement generally comes when u r working on website development. And generally we create this type of table by typing some html syntax of Table, TR, TH, TD etc. and than fulfill the requirement accordingly,

my $sth = $dbh->prepare( "select id, name, status from mytable where something = ... " );
$sth->execute() or die "Failed to query";
while (my $row = $sth->fetchrow_hashref) {

Here we fill the column with the database values.

}

$sth->finish;

Every time, whenever this type of requirement arise, same type of code implies. But HTML::Table makes things better by taking out most of the HTML drudgery, but you still need to loop through adding rows to your table.

This is where HTML::Table::FromDatabase comes in - it’s a subclass of HTML::Table which accepts an executed DBI statement handle, and automatically produces the table for you.

For instance:

my $sth = $dbh->prepare(
"select id, name, status from mytable where something = ..."
);
$sth->execute() or die "Failed to query";

my $table = HTML::Table::FromDatabase->new( -sth => $sth );
$table->print;

This is the very simple way to do it, You can also include more option as required. As HTML::Table::FromDatabase is a subclass of HTML::Table, all of HTML::Table’s options can still be used to control how the generated table appears, for example:

* -class => ‘classname’ to give the table a specific class to help you apply CSS styling
* -border => 1 to apply borders, -padding => 3 to set cell padding
* -evenrowclass and -oddrowclass if you want to have different styling for even and odd rows (e.g. alternating row backgrounds).

The full list of options can be found in the HTML::Table documentation.

4 comments:

  1. Why don't you recommend DBIx::Class for database access?

    ReplyDelete
  2. In this post i tried to show how to use HTML::Table::FromDatabase modules, so i used simple one.

    ReplyDelete
  3. Thanks for posting, I like this blog!

    clomid

    ReplyDelete
  4. PAPISLOT adalah situs judi online yang terpercaya di Indonesia. Dimana kami adalah salah satu situs judi bola online, casino online dan situs judi slot online terbaik yang mencakup seluruh bidang permainan game online. PAPISLOT kini hadir sebagai salah satu judi slot online Indonesia yang didukung oleh customer service profesional online 24 jam dan anda bisa menghubungi kami via livechat , SMS maupun telepon.

    ReplyDelete