#! /usr/local/bin/perl
# Title Update Lab: Solution
#
# Begin loading the needed extensions
#
use DBI; # The DBI extension
use CGI qw (:html2 :form); # The CGI extension
use CGI::Carp qw (carpout); # The extra carping routine
#
# The file dbtype.pl sets a variable which determines the type of database
# you will use. This file will be found in either /tmp or /temp.
#
use lib qw(/tmp /temp);
require 'dbtype.pl';
#
# Set the path, unbuffer STDOUT, and redirect errors to the browser
#
$ENV{PATH} = join ":", qw(/usr/bin /bin /sbin /usr/sbin /etc);
$| = 1;
carpout(\*STDOUT);
#
# Declare variables
#
my( $dbh, $rv, $sth );
my( $tid, $price );
#
# Accept the CGI request
#
my( $q ) = new CGI;
#
# Read values from the form which called us
#
$price = $q->param("price") || 0;
$tid = $q->param("title_id") || 0;
#
# Send the HTTP header
#
print $q->header;
#
# Set the
and send
#
print start_html("Nile dot Com Title Update");
#
# Verify the validity of the values from the form
#
$tid > 0 or later("Title ID must be a number greater than zero!");
$price > 0 or later("Price must be a number greater than zero!");
#
# Attempt to load the driver and connect to the database
#
eval {
$dbh = DBI->connect("DBI:$DB_type:test_nile", $DB_login, $DB_password);
};
#
# Check if the eval failed (driver failed to load)
#
if ($@) {
die "Could not install driver ($DBI::err): $DBI::errstr\n";
}
#
# Check if the connection attempt was successful
#
defined($dbh) or die "Could not connect to db ($DBI::err): $DBI::errstr\n";
#
# Check if the book is in the title table
#
in_table($dbh, $tid) or later("Title id \"$tid\" is not in the table!");
#
# Prepare the following SQL statement and receive a statement handle
#
$sth = $dbh->prepare(qq{
UPDATE title SET
price=$price
WHERE title_id=$tid
}) or die "Prepare of UPDATE: ", $dbh->errstr, "\n";
#
# Execute the prepared SQL statement
#
$sth->execute or die "Execute of UPDATE: ", $dbh->errstr, "\n";
#
# Check the return value from the UPDATE statement
#
$sth->rows == 0
and later("No rows were updated! Did you specify a correct title id?");
$sth->rows > 1
and later("Multiple rows were updated! How did that happen?");
#
# We're done with this statement, free up the resources
#
$sth->finish;
#
# Disconnect from the database, we're done!
#
$dbh->disconnect or warn "Disconnect: ", $dbh->errstr, "\n";
#
# Print out a nice big header,
#
print h1("Title Update");
print "Updating of title id $tid
";
print "New price of $price was successful.
";
#
# Send