- connect mysql database within CGI
- #! /usr/bin/perl -wT
- #@ MAIN_LOGIC
- # todo1.pl - initial version of to-do application
- use strict;
- use lib qw(/usr/lib/perl5/);
- use CGI qw(:standard);
- use WebDB;
- use Dumpvalue;
- my $dumper = new Dumpvalue();
- use Carp qw(cluck);
- print header(),
- start_html(-title => "To-Do List", -bgcolor => "white"),
- h2("To-Do List");
- # Dispatch to proper action based on user selection
- # select STDERR;
- # print("These were the parametersn");
- # my @parameters = param();
- # $dumper->dumpValue(@parameters);
- # select STDOUT;
- my $choice = lc(param("choice")); # get choice, lowercased
- cluck("choice is $choice");
- if ($choice eq "") # initial script invocation
- {
- display_entry_form();
- }
- elsif ($choice eq "submit")
- {
- insert_item(param("content"));
- display_entry_form();
- }
- else
- {
- print p("Logic error, unknown choice: $choice");
- }
- print end_html();
- #@ MAIN_LOGIC
- exit (0);
- # ----------------------------------------------------------------------
- # Insert new to-do item if the content is non-empty.
- #@ INSERT_ITEM
- sub insert_item
- {
- my $content = shift;
- my $dbh;
- $content =~ s/^s+//; # strip leading whitespace
- $content =~ s/s+$//; # strip trailing whitespace
- if ($content ne "") # if content is non-empty, add to table
- {
- 58 $dbh = WebDB::connect();
- 59 $dbh->do(qq{
- INSERT INTO todo SET t = NOW(), status = 'open', content = ?
- }, undef, $content);
- 60 $dbh->disconnect();
- }
- }
- #@ INSERT_ITEM
- # Display entry form
- #@ DISPLAY_ENTRY_FORM
- sub display_entry_form
- {
- print start_form(-action => url()),
- "To-do item:", br(),
- textarea(-name => "content",
- -value => "",
- -override => 1,
- -rows => 3,
- -columns => 80),
- br(),
- submit(-name => "choice", -value => "Submit"),
- end_form();
- }
- #@ DISPLAY_ENTRY_FORM
- package WebDB;
- #package WebDB for later use;
- use strict;
- use DBI;
- my $db_name="webdb";
- my $user_name="webdev";
- my $password="webdevpass";
- my $host_name="localhost";
- my $dsn = "DBI:mysql:host=$host_name; database=$db_name";
- #connect to MySQL server, using hardwired name and password
- sub connect
- {
- return (DBI->connect($dsn, "webdev", "webdevpass",
- {PrintError=>0, RaiseError=>1}));
- # || die "Could not connect to database: $DBI::errstr";
- }
- #Connect to MySQL server, using name and password from the current
- #user's ~/.my.cnf option file. The mysql_read_default_file option,
- #when added to the DSN, specifies which option file to read.
- #sub connect_with_option_file
- #{
- # #$dsn .= ";mysql_read_default_file=$ENV{HOME}/.my.cnf";
- # $dsn .= ";mysql_read_default_file=/etc/mysql/my.cnf";
- # return (DBI->connect ($dsn, undef, undef, {PrintError=>0, RaiseError=>1}));
- #}
- 1; #return true
- [error] [client 127.0.0.1] DBD::mysql::db do failed: No database selected at /usr/lib/cgi-bin/DuBois/todo1.pl line 59., referer: http://localhost/cgi-bin/DuBois/todo1.pl