5% assure discount from here only

Showing posts with label database value. Show all posts
Showing posts with label database value. Show all posts

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.