HTML, XHTML and CSS All-In-One for Dummies - Andy Harris [242]
♦ The user doesn’t know SQL. Even if the user does know SQL, don’t let him use it. The SQL query should always be built on the server side. Get enough information to build an SQL query, but don’t send a query to the PHP. Doing so exposes your database to significant abuse, such as the SQL injection attack described later in this chapter.
♦ The form uses the post mechanism. From the XHTML perspective, it isn’t important whether the form uses get or post, but when you’re using forms to construct SQL queries, using post is a bit safer because it makes the bad guys work a little bit harder to spoof your site and send bogus requests to your database.
Building an XHTML search form
This is what the XHTML code for search.html looks like:
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
type = “text/css“
href = “search.css“ />
Search my contacts
This is really a pretty basic form. The interesting stuff happens in the search.php program that’s triggered when the user submits this form.
Responding to the search request
When the user submits search.html, a page like Figure 7-5 appears, created by search.php.
Figure 7-5: The program searches the database according to the para-meters in search.html.
The search.php program isn’t really terribly different from contactTable.php. It takes an SQL query, sends it to a database, and returns the result as an XHTML table. The only new idea is how the SQL query is built. Rather than preloading the entire query into a string variable, as I did in all other examples in this chapter, I used input from the form to inform the query. As usual, I provide the code in its entirety here, and then I point out specific features. Look at the big picture first:
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
My Contacts
$sql = processInput();
printResults($sql);
function processInput(){
//extract information from previous form and build a safe query
$srchVal = $_POST[“srchVal“];
$srchField = $_POST[“srchField“];
$srchVal = mysql_real_escape_string($srchVal);
$srchField = mysql_real_escape_string($srchField);
$sql = “SELECT * FROM contact WHERE $srchField LIKE ‘%$srchVal%’“;
return $sql;
} // end processInput
function printResults($sql){
$conn = mysql_connect(“localhost“, “user“, “password“);
mysql_select_db(“xfd“);
$result = mysql_query($sql, $conn);
print “
| $field->name | \n“;
|---|