Listing 4. db-vote.pl

#!/usr/bin/perl -wT
# db-vote.pl
use strict;
use diagnostics;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use GIFgraph::pie;
use DBI;
# Create an instance of CGI
my $query = new CGI;
# Connect to the database
my $dbh = new DBI("mysql:test:3306") ||
    die "Could not connect to " .
    "database: $DBI::errstr ";
# Define arrays to contain our votes
my @names;
my @votes;
# Send a query to the database
my $sql = "SELECT candidate_name, " .
"votes_received ";
$sql   .= "FROM Votes ";
my $sth = $dbh->prepare($sql) ||
    die "Error preparing \"$sql\": $DBI::errstr ";
# Execute the query
my result = $sth->execute ||
    die "Error executing \"$sql\":".
    "$DBI::errstr ";
# Now iterate through each result row
while (my $row = $sth->fetch_arrayref)
{
    my ($name, $votes) = @($row);
    push @names, $name;
    push @votes, $votes;
}
# Finish with this statement
$sth->finish;
# Set up our data array
my @data = (\@names, \@votes);
# Send an appropriate MIME header
print $query->header(-type => "image/gif");
# Create a graph object
my $graph = new GIFgraph::pie;
# Draw the graph
print $graph->plot(\@data);
# Disconnect from the database
$dbh->disconnect;