Listing 2: cgi-insert-test.pl.
#!/usr/bin/perl -w
# This program uses CGI to insert a
# random value into a table in the database.
#
use strict;
use diagnostics;
use CGI;
use DBI;
# Create an instance of CGI
my $query = new CGI;
# Send an appropriate MIME header
print $query->header("text/html");
# Connect to the database
my $dbh = DBI->connect("DBI:mysql:test:127.0.0.1");
# If we could not connect, return an error
&log_and_die($DBI::errstr) unless $dbh;
# Get a large random number
my $random = rand(10000);
# Insert the new value into test_insert
my $sql = "INSERT INTO test_insert (contents) VALUES
(\"$random\") ";
# Find out if the insert was successful
my $successful_insert = $dbh->do($sql);
# Print a short response string if it was
print "<P>Success!</P>\n" if $successful_insert;
# Disconnect from the database
$dbh->disconnect;
Copyright © 1994 - 2018 Linux Journal. All rights reserved.