Perl Source Code: dbwrite.pl
#!/usr/bin/perl
use CGI qw(:standard);
use DBI;
use DBD::mysql;
use common;
use connect;
#----------------------------------------------------------
# The Web Language Project
# Mark Brautigam
# May-June 2015
# http://www.mixed-up.com/markb/
#----------------------------------------------------------
myUtils::headers1();
myUtils::headers2();
print myUtils::sidebar ("perl", "dbwrite", "pl");
print <<middle;
<div id="content">
<h2>Perl: Write to MySQL Database</h2>
middle
print_form ();
if (param ('submit') &&
(param('site') || param('state') || param('city') || param('lat') || param('lon') ) ) {
my $state = param('state');
my $lat = param('lat');
my $lon = param('lon');
if ($lat == '') {
$lat = 0;
}
if ($lon == '') {
$lon = 0;
}
if (length ($state) > 4) {
$state = substr ($state, 0, 4);
}
print_feedback ($state, $lat, $lon);
$dbh = connect::my_connect();
$sql = sprintf ("INSERT INTO parks VALUES ('%s', '%s', '%s', %s, %s, null);",
param('site'), $state, param('city'), $lat, $lon);
print $sql;
my $sth = $dbh->prepare ($sql);
$sth->execute();
}
print <<foot;
<p><a href='dbread.pl'>Show the contents of this database table »</a></p>
<p><a href='source.pl?f=8'>Show Perl source code »</a>
</div>
foot
myUtils::footers();
#----------------------------------------------------------
sub print_feedback
#----------------------------------------------------------
{
my $state = $_[0];
my $lat = $_[1];
my $lon = $_[2];
print "<p>The following data was entered in the data file: </p>\n";
print "<table class='results'>\n";
printf (" <tr><td>Park</td><td>%s</td></tr>\n", param('site'));
printf (" <tr><td>City</td><td>%s</td></tr>\n", param('city'));
printf (" <tr><td>State</td><td>%s</td></tr>\n", $state);
printf (" <tr><td>Latitude</td><td>%s</td></tr>\n", $lat);
printf (" <tr><td>Longitude</td><td>%s</td></tr>\n", $lon);
print "</table>\n";
}
#----------------------------------------------------------
sub print_form
#----------------------------------------------------------
{
print <<form;
<form name='parksform' action='dbwrite.pl' method='POST'>
<fieldset class='db'>
<legend>Add a park</legend>
<table>
<tr><td>Park:</td><td><input type='text' name='site' /></td></tr>
<tr><td>City:</td><td><input type='text' name='city' /></td></tr>
<tr><td>State:</td><td><input type='text' name='state' /> <span>(4 characters max)</span></td></tr>
<tr><td>Latitude:</td><td><input type='text' name='lat' /></td></tr>
<tr><td>Longitude:</td><td><input type='text' name='lon' /></td></tr>
<tr><td></td><td><input type='submit' id='submit' name='submit' value='Add' /></td></tr>
</table>
</fieldset>
</form>
form
}