next up previous contents index
Next: Configuring Apache Up: Web Server Previous: Creating Cookies   Contents   Index


Database

You can add the database element to a CGI program quite easily. Make sure that you have completed the MySQL installation in Chapter 11 before you try using DBI in CGI programs. Let's now take the example Perl program that used DBI and turn it into a CGI program /var/www/cgi-bin/dbitest.cgi:

#!/usr/bin/perl

use DBI;

$dsn = "DBI:mysql:bob:localhost"; #data source name
$user_name = "bob"; # user name
$password = ""; # passwords are either blank or existing

$dbh = DBI->connect($dsn, $user_name, $password, { RaiseError => 1});

print "Content-type: text/html\n\n";

print "<html>\n";
print "<head>\n";
print "<title>dbitest.cgi</title>\n";
print "</head>\n";
print "<body bgcolor=ffffff>\n";
print "<h1>dbitest.cgi</h1>\n";
print "<ul>\n";

$count = 0;
$infoget = "SELECT * FROM messages";
$sth = $dbh->prepare ($infoget);
$sth->execute();
while(@info = $sth->fetchrow_array()) {
    ($num, $sender, $message) = @info;
    print "<li>$num ($sender) - $message\n";
    $count++;
}

print "</ul>\n";
print "$count Message(s)<br>\n";

print "</body>\n";
print "</html>\n";

exit;

Once you have the program there and permissions set, go and take a look at it. With DBI programs, since they are Perl programs you can debug them by running them from the shell most of the time.



Joseph Colton 2002-09-24