A Start With SQL and Relational Databases
#!/usr/bin/perl -w
use DBI;
use CGI qw(:all);
use CGI::Carp qw(fatalsToBrowser); # Makes die work acceptably! Very important!!
print header(), start_html("Email Signup");
print h1("Mailing List Signup");
print p("Please fill out this form and you will be notified via
email about updates and future product announcements");
# Connect to the database if first time the script is called.
$db = DBI->connect("DBI:CSV:f_dir=.") ||
die "Cannot connect: $DBI::errstr\n";
# Better to create the table definition in the database itself
# rather than a script. But here's what it looks like!
if (!-e "namedata")
{
$cmd = $db->prepare("CREATE TABLE namedata (
first varchar(32) not null,
last varchar(32) not null,
email varchar(32) not null)");
$cmd->execute() || die "Cannot create table!\n";
}
# Did user hit the submit button?
if (param("Submit User Data"))
{
$first = param('first name');
$last = param('last name');
$email = param('email');
if (!$first || !$last || !$email) {die "Missing Field!\n"}
$first = ucfirst(lc $first);
$last = ucfirst(lc $last);
# Prepare an insert statement. Get object handle back!
$rows = $db->prepare(
"INSERT INTO namedata (first, last, email)
VALUES ('$first', '$last', '$email')") ;
# Run the prepared insert statement.
$rows->execute();
}
# If user hit 'End Session' button, show all the rows in the database!!
if (param('End Session')) {
$statement = "SELECT * from namedata";
$doit = $db->prepare($statement);
$doit->execute();
while (($first, $last, $email) = $doit->fetchrow_array)
{print p("data: $first, $last, $email\n\n")}
$db->disconnect() || die "Cannot disconnect\n";
}
print start_form();
print p("First Name: ",textfield(-name => 'first name')),br,
p("Last Name: ", textfield(-name => 'last name')),
p("Email: ", textfield(-name=> 'email')), hr,
p(submit(-name => 'Submit User Data')),
p(submit(-name => 'End Session'));
print end_form, end_html;