#!/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=""; my $authorlast=""; my $authorfirst="";

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


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

if (! defined ($cgi->param("authorlast"))) 
{ $authorlast=$cgi->param("authorlast"); }

$authorfirst=$cgi->param("authorfirst");

print $cgi->h1("Your input 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="insert into books (title, lastname, firstname) values (\""
    . $title . "\",\"" . $authorlast . "\",\"" . $authorfirst . "\")";

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

print "your query=" . $query . "\n";

# Done:
$dbh->disconnect;

doform();


exit;

sub doform {

    print "<form method=POST action=\"/~gbnewby/November29/db5.cgi\">";
    print "<p>Book title:<input type=text name=\"title\" size=50></p>\n";
    print "<p>Author lastname:<input type=text name=\"authorlast\" size=50></p>\n";
    print "<p>Author firstname:<input type=text name=\"authorfirst\" size=50></p>\n";
    print "<br>\n";
    print "<p><input type=submit value=\"Click to Input this entry\"></p>\n";
    print "</form>\n";
}


