Listing 2. register.pl


#!/usr/bin/perl

use
strict;
use diagnostics;
use warnings;

use
CGI;
use DBI;
# ------------------------------------------------------------
# # Connect to the database
# ------------------------------------------------------------
# my $dbname = 'atf';
my $dbuser = 'reuven';
my $dbpassword = '';

my
$dbh = DBI->connect("DBI:Pg:dbname=$dbname",
                              $dbuser, $dbpassword,
{
                        AutoCommit => 1, RaiseError => 1,
PrintError => 1, ChopBlanks => 1}) ||
    print "<p>Error connecting: '$DBI::errstr' </p>";

# ------------------------------------------------------------
# CGI startup
# ------------------------------------------------------------
my $query = new CGI;
print $query->header("text/html");
print $query->start_html(-title => "Site registration");

my $username = $query->param("username");
my $password = $query->param("password");
my $email_address = $query->param("email_address");

# ------------------------------------------------------------
# Check the parameters
# ------------------------------------------------------------
my @missing_data = ();

push @missing_data, "The username"
    unless $username;

push @missing_data, "A password"
    unless $password;

push @missing_data, "The e-mail address"
    unless $email_address;

if (@missing_data)
{
    foreach my $missing_field (@missing_data)
    {
        print "<p>Sorry, but you are missing:</p>\n";
        print "<ul>\n";
        print "<li> $missing_field</li>\n";
        print "</ul>\n";
        print "<p>Please back up and try again.</p>\n";
        exit;
    }
}


# ------------------------------------------------------------
# Try to register the user
# ------------------------------------------------------------
my $select_sql = "SELECT COUNT(*) FROM Users WHERE username = ?";
my $select_sth = $dbh->prepare($select_sql);
$select_sth->execute($username);

my ($username_is_taken) = $select_sth->fetchrow_array();

# Is this username taken?  If so, give an error
if ($username_is_taken)
{
    print "<p>Sorry, but the username '$username' was already taken.
Please back up and try again.</p>\n";
}

# Otherwise, insert the new trio into the
database
else
{
    my $insert_sql = "INSERT INTO Users (username, password,
email_address)
                                    VALUES (?, ?, ?)";
    $dbh->do($insert_sql, {}, $username, $password, $email_address);

    print "<p>Added the username '$username' to the system!</p>\n";
}

print $query->end_html;

