Archive for the 'perl' Category

Creating HTML tables from database queries with HTML::Table::FromDatabase

A task I find myself doing reasonably often when programming is producing a HTML table based on the result of a database query.

This often ends up with the same kind of boring code being written again and again, which get tedious.

For example:

print <<TABLESTART;
<table border="1">
<tr><th>id</th><th>foo</th><th>bar</th></tr>
TABLESTART
 
my $sth = $dbh->prepare(
    "select id, foo, bar from mytable where something = 'somethingelse'"
);
$sth->execute() or die "Failed to query";
 
while (my $row = $sth->fetchrow_hashref) {
    print '<tr><td>';
    print join '</td><td>', @$row{qw(id foo bar)};
    print "</td></tr>\n";
}
print "</table>\n";
$sth->finish;

Not hard, but it does get tedious.

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 my 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, foo, bar from mytable where something = 'somethingelse'"
);
$sth->execute() or die "Failed to query";
 
my $table = HTML::Table::FromDatabase->new( -sth => $sth );
$table->print;

Much easier, and HTML::Table::FromDatabase does all the tedious work.

Sometimes that won’t be quite flexible enough though; you might have something you want to do to certain columns or values before outputting them.

That’s where HTML::Table::FromDatabase’s callbacks come in handy. For a basic example, let’s say that one of the columns you’re fetching contains URLs, and you want to wrap them in anchor tags to make them clickable links. Simply done with:

 my $table = HTML::Table::FromDatabase->new(
    -sth => $sth,
    -callbacks => [
        {
            column => 'url',
            transform => sub { $_ = shift; qq[<a href="$_">$_</a>]; },
        },
    ],
 );

Another example - looking for all cells whose value is a number, and formatting them to two decimal places:

 my $table = HTML::Table::FromDatabase->new(
    -sth => $sth,
    -callbacks => [
        {
            value => qr/\d+/,
            transform => sub { return sprintf '%.2f', shift },
        },
    ],
 );

You can apply as many callbacks as you need.

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, I’m not going to duplicate it all here.

Currently, the row headings used in the generated table are taken from the column names in the query, but I plan to release a new version sometime soon which allows you to alias them, if you want to do so.

(The code samples in this post are intentionally kept relatively simple, omitting obvious things like connecting to the database first, error checking etc).

(This post also appears on Perlbuzz)

Playing with Ohloh

I’ve been having a quick play with Ohloh, and it seems pretty good. It’s “a website which provides a web services suite and online community platform that aims to map the landscape of open source software development.”

I figured it was worth getting my Perl modules listed, if only to boost the amount of Perl code listed there - I don’t think enough people sing Perl’s praises as they’re busy doing real work with it, so it appears to some to be going “the way of the dinosaurs”.

Ohloh seems impressive so far, with features to hook in to your source control system (Subversion in my case) to see contributors, change history etc. The only drawback is that it does not like re-organisation of the repo, and I re-organised mine to get all the code I’m willing to publically expose under a certain path in the repo, so I can point svnserve at that path, whilst some other code sits at another level. This means that, as far as Ohloh can see, there’s only ever been one commit to my projects. It’s a known problem (according to this forum post).

So far I’ve added SMS::AQL and HTML::Table::FromDatabase - other projects to follow.

HTML::Table::FromDatabase released

I’ve just released a new Perl module to CPAN, HTML::Table::FromDatabase. It’ll hit CPAN mirrors soon.

It subclasses HTML::Table, and its purpose is to simplify a fairly common task, of taking data from a database query and displaying it in a HTML table.

Continue reading ‘HTML::Table::FromDatabase released’

New song lyrics search site

A whistling badger

I’ve been meaning to whack up a post about this - I launched a new song lyrics search website the other day called LyricsBadger.

It uses my Lyrics::Fetcher Perl module to fetch song lyrics from a variety of sites, and remembers what it’s been asked for before so that it can present lists of artists/songs which it’s already been asked for.

I built it as a testbed for Lyrics::Fetcher and to get some experience with Template Toolkit for Perl (which absolutely rocks!). The entire site is powered by one Perl script and a handful of templates, and uses a ScriptAlias directive to pass all requests to the one script so that it can provide nice clean URLs like /lyrics/Artist/Title.

Why not go and give LyricsBadger a try?

Updated DNS propagation tracker

Updated my DNS propagation tracker, so that you can specify a set of nameservers to query rather than using a random set, or enter a domain to query the nameservers listed for that domain (useful if you want to check that all nameservers for your domain are giving the same answer).

Here it is: DNS propagation tracker

SimpleStreamer - Flash video streamer for Wii or PC

I recently got a Wii as a new toy, and wanted something good to stream videos to it.

I had a look round at some of the various “Media Center” options out there, but didn’t find anything I liked, so I’m writing my own.

So far I have a working system in Perl which allows you to browse the pre-set video dir(s) and presents a list of files + folders, when you select one it then uses a Flash streaming player, and either presents the file directly if it was a .flv video, otherwise it uses ffmpeg to transcode it to FLV on the fly and stream it to the Flash player.

Continue reading ‘SimpleStreamer - Flash video streamer for Wii or PC’

SMS::AQL reaches 100% “Kwalitee” score

Version 0.04 of SMS::AQL which I released the other day gets a 100% “Kwalitee” score on CPANTS (the CPAN Testing Service) - see the report.

Thanks to Altinity for featuring SMS::AQL in their Opsview package and for mentioning it on their blog.

And, you might be asking, just what is "Kwalitee"? Well, it’s a sort-of made up measure of code quality… read the full explanation.

SMS::AQL 0.04 released

Finally released SMS::AQL v0.04 to CPAN last night, incorporating improvements kindly submitted by Ton Voon from Altinity.  Thanks Ton!

The changes include better parsing of server responses, documentation improvements, and a new test script using Test::MockObject to exercise the module without actually interacting with AQL or sending messages.   Brilliant stuff.

Altinity look to be a nice company  doing Open-Source data centre management tools, and actively support Open-Source projects by contributing code and bug fixes.

Lyrics::Fetcher v0.4.0 released to CPAN

Just released version v0.4.0 of Lyrics::Fetcher to CPAN… it’ll take a little while to be distributed to the various CPAN mirrors.

Version 0.4.0 introduces the ability to automatically try all available fetcher modules until one suceeds, or pass an arrayref of fetchers to try in order.  Lyrics::Fetcher::LyricsNet has been removed from the package until it can be fixed up (the LyricsNet search doesn’t seem to work at the moment).

Lyrics::Fetcher::LyricWiki 0.01 released

I’ve just written a Perl module to fetch lyrics from www.lyricwiki.org and released it to CPAN.

It’s a fetcher designed to be used with Lyrics::Fetcher (although you can also use it directly without Lyrics::Fetcher).

Get Lyrics::Fetcher::LyricWiki on CPAN now (it’s just been released and will take a little while to reach all the mirrors so if it’s not there when you read this, give it a little while :) )



get some tasty email addresses here