return to first page linux journal archive
keywordscontents

Listing 1.

#!/usr/bin/perl -w

use strict;
use diagnostics;
# available from http://www.perl.com/CPAN/
use CGI;  
use Mysql;

# ----------------------------------------
# Name some global variables
my $sender_name = "";
my $sender_email = "";
my $recipient_name = "";
my $graphic_name = "";
my $postcard_text = "";

# Create an instance of CGI
my $query = new CGI;

# Send an appropriate MIME header
print $query->header("text/html");

# Get the name to match from the query string
my $id = $query->param("keywords");

# Check that the user entered a postcard ID
if ($id == 0)
{
    print $query->start_html(-title => 
	"No ID given!");
    print "<P>Sorry, but I can retrieve ";
    print "postcards only when an ID number is ";
    print "provided. Please enter one, and I ";
    print "will try to find a postcard ";
    print "matching that ID number.</P>\n";
    print "<isindex>\n";
    print $query->end_html;
    exit;
}
# Connect via Unix sockets to the database on 
# this server
my $dbh = Mysql->connect("localhost", "test");

# Build up our SQL command
my $command = "";
$command = "select sender_name,sender_email,";
$command .= "recipient_name,graphic_name,";
$command .= "postcard_text from postcards ";
$command .= "where id_number = $id";

# Uncomment for debugging
# print "<P>SQL command: \"$command\"</P>\n";
# Send the query
my $sth = $dbh->query($command);

# Make sure that $sth returned reasonably
die "Error with command \"$command\"" 
	unless (defined $sth);

# Report an error if no rows are returned
if ($sth->numrows == 0)
{
    print $query->start_html(-title => 
	"Invalid ID!");
    print "<P>Sorry, but the ID number you ";
    print "provided does not match any postcard";
    print "in my database. Please try again, ";
    print "and I will try to find a postcard ";
    print "matching that ID number.</P>\n";
    print "<isindex>\n";
    print $query->end_html;
    exit;
}
# ----------------------------------------------------
# Iterate through the returned rows
my @arr = ();

while (@arr = $sth->fetchrow)
{
    # Assign our variables to the returned row
    ($sender_name, $sender_email, $recipient_name, 
     $graphic_name,  $postcard_text) = @arr;
}
# ----------------------------------------------------
# Begin the HTML output
print $query->start_html(-title =>
	"Postcard for $recipient_name");

print "<img src=\"/tmp/$graphic_name\"</P>\n";
print "<P><pre>$postcard_text</pre></P>\n";
print "<P>From $sender_name ($sender_email)</P>\n";

# End the HTML
print $query->end_html;

exit;