#!/usr/bin/perl -Tw use DBI; use CGI; use HTML::Template; use strict; my $DBH = DBI->connect( qw(DBI:mysql:mp3:host user pass), { RaiseError => 1 }, ); my $CGI = CGI->new(); my @COLS = (qw(title artist album)); # verify the sort param - never trust user input my %sort_lookup = map {$_ => $_} @COLS; my $sort = $sort_lookup{$CGI->param('sort')||''} || 'title'; my $data = $DBH->selectall_arrayref(" select @{[join(',', @COLS)]} from songs order by ? ", undef, ($sort)); # prepare the DS for the headers my $headers = [ map {{ URL => $CGI->script_name . "?sort=$_", LINK => ucfirst($_), }} @COLS ]; # prepare the DS for the rows my $i; my $rows = [ map { my $row = $_; (++$i % 2) ? { ODD => [ map { {VALUE => $_} } @{$row} ] } : { EVEN => [ map { {VALUE => $_} } @{$row} ] } } @{$data} ]; # remove excess blood from ears after that last expression # read the template as a scalar from DATA my $html = do { local $/; }; # prepare the template and substitute the values my $template = HTML::Template->new( scalarref => \$html, loop_context_vars => 1, ); $template->param( HEADERS => $headers, ROWS => $rows, SORT => $sort, ); # print the goods print $CGI->header(); print $template->output(); $DBH->disconnect(); __DATA__ Songs sorted by <TMPL_VAR NAME=SORT>

Songs sorted by