Ruby Source Code: dbwrite.rb
#!/usr/bin/ruby
require 'cgi'
#require 'mysql'
#require './connect'
require './common'
#----------------------------------------------------------
# The Web Language Project
# Mark Brautigam
# May-June 2015
# http://www.mixed-up.com/markb/
#----------------------------------------------------------
cgi = CGI.new
puts cgi.header
headers1()
headers2()
print sidebarX("ruby", "dbwrite", "rb")
print %q(
<div id="content">
<h2>Ruby: Write to MySQL Database</h2>
<p class='error'>Ruby database functions are not installed on this server.</p>
<form name='parksform' action='dbwrite.rb' 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>
)
#----------------------------------------------------
def is_number (s)
#----------------------------------------------------
#http://stackoverflow.com/questions/5661466/test-if-string-is-a-number-in-ruby-on-rails
true if Float(s) rescue false
end
#----------------------------------------------------
# The main Ruby code is here.
#----------------------------------------------------
site = cgi['site']
city = cgi['city']
state = cgi['state']
lat = cgi['lat']
lon = cgi['lon']
submit = cgi['submit']
if (submit == "Add" && formHasData([site, city, state, lat, lon]))
# Integer considerations
if (lat == '')
lat = 0
end
if (lon == '')
lon = 0
end
if (!is_number (lat))
lat = 0
end
if (!is_number (lon))
lon = 0
end
if (state.length > 4)
state = state[0..3]
end
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", site);
printf(" <tr><td>City</td><td>%s</td></tr>\n", 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";
# The acutal database connection happens here
con = my_connect()
sql = sprintf("INSERT INTO parks VALUES ('%s', '%s', '%s', %s, %s, null);",
site, state, city, lat, lon);
print sql;
rs = con.query(sql);
end
#----------------------------------------------------
print %q(
<p><a href='dbread.rb'>Show the contents of this database table »</a></p>
<p><a href='source.rb?f=8'>Show Ruby source code »</a>
</div>
)
footers()