#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use DBI;
use strict;

print header;    # print the content-type header

my $dbh = DBI->connect( "dbi:mysql:products", "webserver", "" )
  or &dienice("Can't connect to database: $DBI::errstr");

my $uri = $ENV{'REQUEST_URI'};
unless ($uri) {
    exit;    # don't update a blank counter.
}

# remove "index.html" from the end of the URI, so that 
# "/ch18/index.html" becomes "/ch18/".
if ( $uri =~ /(.*)index.html/i ) {
    $uri = $1;
}

# also remove any duplicate //'s in the url
$uri =~ s#//#/#g;

my $sth = $dbh->prepare("select count from counts where pagename=?") or &dbdie;
$sth->execute($uri) or &dbdie;

my $count;
if ( $count = $sth->fetchrow_array ) {
    $count++;
    $sth = $dbh->prepare("update counts set count=count+1 where pagename=?") or &dbdie;
    $sth->execute($uri) or &dbdie;
}
else {
    $count = 1;
    $sth   = $dbh->prepare("insert into counts values(?,?)") or &dbdie;
    $sth->execute($uri, 1) or &dbdie;
}
print "You are visitor number $count.\n";
$dbh->disconnect;

sub dienice {
    my ($errmsg) = @_;
    print qq(<h2>Error</h2>\n);
    print qq(<p>$errmsg</p>\n);
    exit;
}

sub dbdie {
    my($package, $filename, $line) = caller;
    my($errmsg) = "Database error: $DBI::errstr<br>
                called from $package $filename line $line";
    &dienice($errmsg);
}