Databases Reference
In-Depth Information
Example 18-3. The CGI Animal list script rewritten with CGI functions
#!/usr/bin/perl
use strict;
# Connect to the MySQL server, run the query, store the result
use DBI;
my $dbh=DBI->connect("DBI:mysql:host=localhost;database=AnimalDB",
" the_username ",
" the_password ",
{PrintError=>0, RaiseError=>1});
my $results = $dbh->selectall_hashref('SELECT * FROM Animals', 'Name');
$dbh->disconnect();
# Prepare and display the results in HTML format
use CGI ':all';
my @AnimalsDataArray;
foreach my $Name (keys %$results)
{
my $AnimalsDataArrayRow =
th({-align=>"LEFT", -bgcolor=>"SKYBLUE"}, $Name).
td({-bgcolor=>"PINK"}, [$results->{$Name}->{Count}]);
push @AnimalsDataArray, $AnimalsDataArrayRow;
}
my $result=
header(-type=>"text/html", -charset=>'UTF-8').
start_html(-title=>"List of Animals", -encoding => 'UTF-8').
h1("Pet roll call").
table(
{-border=>'true'},
Tr({-align=>"CENTER",-valign=>"TOP", -bgcolor=>"LIGHTGREEN"},
[th(['Name','Count'])]),
Tr([@AnimalsDataArray])
).
end_html;
print $result;
Instead of printing out the table rows one by one, this example defines the array
$AnimalsDataArray , and uses the push command to append each row of data to this
array. We build up the $result string using functions provided by the CGI module and
place @AnimalsDataArray in a table row. Finally, we print the whole $result string.
The charset parameter of the header( ) function and the encoding parameter of the
start_html( ) function are optional, and are used to specify the character encoding
that's used in the document. Together, they help the browser determine the appropriate
fonts to use to correctly display the page. If you omit these parameters, the default value
ISO-8859-1 will be used.
 
Search WWH ::




Custom Search