Page 215 - Open Soource Technologies 304.indd
P. 215
Unit 9: Web Techniques
<option value=”F” Notes
<? if($varGender==”F”) echo(“ selected=\”selected\””);?> >Female
</option>
</select>
</p>
This code is not the easiest to look at! Basically what is happening here is that for whatever option
the user has already selected, we want to put a selected=”selected” property in that option box.
Now the select box choice will be preserved when the form is submitted.
If this code seems ugly, do not worry. Many select boxes will be populated from a database
table, and would not require you to write a bunch of embedded “if” statements. Also, using a
select box for ‘Gender’ probably is not the best choice: radio buttons might make more sense.
9.4.4 Saving the Form Data to a MySQL Database
In the previous example, the form data was saved to a text file. This may be useful sometimes,
but usually data is much more easily stored and retrieved in a database. In this example, we
will look at inserting the data into a MySQL table.
For this example, we are going to assume that a table called ‘movieformdata’ already exists
with 3 columns: ‘moviename’, ‘yourname’, and ‘Gender’, and we are going to assume that
moviename and yourname fields can store at least 50 characters, whereas Gender can store at
least 1 character. Hopefully you are familiar with SQL and you recognize this “insert” statement:
INSERT INTO movieformdata (moviename, yourname, Gender) VALUES (‘Jaws’,’Bob’,’M’);
There are three steps to interacting with the database in this form:
• Connect to the database
• Construct a SQL command string
• Execute the SQL command string
To connect to a MySQL database, PHP has some built-in functions:
<?php
$db = mysql_connect(“servername”,”username”,”password”);
if(!$db) die(“Error connecting to MySQL database.”);
mysql_select_db(“databasename” ,$db);
?>
Substitute your information into these functions where necessary. “servername” is usually
“localhost” or something like “mysql.yourisp.com”. The mysql_connect function connects to the
MySQL server. If it fails to connect, the PHP script will die with an error message. Otherwise,
you must then select a database on the server. Once these steps are performed, you now have
a connection to a database, and can start running SQL commands on it.
Now assuming the form is valid, let’s construct a SQL command. It is important to talk about a
security concept here. It will not cover it in-depth, but if you plan to make a public web form,
you should be well-versed in SQL injections and how to prevent them. In the meantime, the
example script contains a “PrepSQL” function that will “sanitize” inputs from the form. Here’s
how to construct the SQL string:
<?php
$sql = “INSERT INTO movieformdata (moviename, yourname, Gender) VALUES (“.
LOVELY PROFESSIONAL UNIVERSITY 209