Listing 1: rank-category.pl, which allows users to add new categories
to the ranking database.

#!/usr/bin/perl -wT
# filename: rank-category.pl

use strict;
use diagnostics;
use CGI::Pretty qw(:standard);
use CGI::Carp qw(fatalsToBrowser);
use DBI;

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

# Send a MIME header
print $query->header("text/html");
print $query->start_html(-title => "Add a new category");

# ------------------------------------------------------------
# If this program was invoked with POST, then retrieve
# the new category name and try to insert it.

if ($query->request_method eq "POST")
{
    # Connect to the database
    my $dbh = DBI->connect("DBI:mysql:test:localhost") ||
	die qq{DBI error from connect: "$DBI::errstr"};

    my $new_category_name = $query->param("new_category_name");
    my $new_category_description = 
	$query->param("new_category_description");

    # Check that there are printable characters
    unless ($new_category_name =~ /\S/)
    {
	print h1("Error with new category"),
	    p("Category names must contain at least one printable character"),
		p("Please try again.");
	exit;
    }

    # Insert the new category
    my $sql  = "INSERT INTO RankCategories ";
    $sql    .= "(category_name, category_description) ";
    $sql    .= "VALUES (?,?) ";

    my $sth = $dbh->prepare($sql) 
	|| die "Cannot prepare: $DBI::errstr";

    my $success =
	$sth->execute($new_category_name, $new_category_description);

    # Finish with the database
    $sth->finish;
    $dbh->disconnect;

    # Print an appropriate message, depending on the INSERT's success 
    if ($success)
    {
	print p("Successfully added the new category ", 
		b($new_category_name), ".");
    }
    else
    {
	print p("Error adding the category ", 
		b($new_category_name), ".  Perhaps it already exists",
		"or contained illegal characters?");
	exit;
    }
}

# ------------------------------------------------------------
# Allow users to add a new category

print h1("Add a new ranking category");

print startform(-method => "POST",
		-action => $query->self_url);

print p("New category:", 
	textfield(-name => 'new_category_name',
		  -size => 25,
		  -override => 1,
		  -maxlength => 25));

print p("Description: ",
	textfield(-name => 'new_category_description',
		  -size => 80,
		  -override => 1,
		  -maxlength => 100));

print submit(-value=>'Add category');
print endform;

print p("Now go ", 
	a({-href=>'/cgi-bin/rank-something.pl'}, "rank something"),
	"!");

print $query->end_html;
