#!/usr/local/bin/perl -w

# Sample database access:

use strict;
use DBI;
use CGI; 
use CGI::Carp "fatalsToBrowser"; 
my $cgi = new CGI; 
print "Content-type: text/html\n\n"; 
print "<html><body>\n";

my $titlecol=0;
my $lastnamecol=1;
my $firstnamecol=2;
my $pubyearcol=3;
my $urlcol=4;
my $publisheridcol=5;

# Function prototype:
sub doform;

# Decision point: did we get a "title" as a query?
my $title="";

# Case 1: No title, just display the form and exit:
if (! defined ($cgi->param("title"))) {
    print $cgi->h1("Query the PG Database");
    doform();
    exit;
}


# Case 2: Yes, we got a title.  Process the query:
$title=$cgi->param("title");
print $cgi->h1("Your query for title=$title");

# Handle to database.  This is for a local socket/file connect,
# but the syntax is similar for a network connect: 
my $dbh = DBI->connect('dbi:mysql:database=pg;file=/var/lib/mysql/mysql.sock', 'pg', 'cs205', { RaiseError => 1} );

# Let's get all the values from a table:
my $query="select * from books where title=\"" . $title . "\"";

print "<p>Second query: <font color=\"green\">$query</font>\n</p>";

my $rows = $dbh->selectall_arrayref($query);

my  $ctr=0;
print "<hr>\n <table border=\"1\">\n";
print "<th><td>Title</td><td>Firstname Lastname</td><td>Pubyear</td><td>URL</td><td>PublisherID</th>\n";
foreach my $row (@$rows) {
    print "<tr><td>#" . ++$ctr . "</td>\n   <td>" .
	$row->[$titlecol] . "</td>\n   <td>" .
	$row->[$firstnamecol] . " " .
	$row->[$lastnamecol] . "  <td>" .
	$row->[$pubyearcol] . "</td>\n   <td>" .
	"<a href=\"$row->[$urlcol]\">" .
	$row->[$urlcol] . "</a></td>\n   <td>" .
	$row->[$publisheridcol] . "</td>\n  </tr>";
}

print " </table>\n";

# Done:
$dbh->disconnect;

doform();


exit;

sub doform {

    print "<form method=POST action=\"/~gbnewby/November29/db4.cgi\">";
    print "<p>Book title:<input type=text name=\"title\" size=50></p>\n";
    print "<br>\n";
    print "<p><input type=submit value=\"Click to Submit Query\"></p>\n";
    print "</form>\n";
}


