Using variables in a SQL query

Một phần của tài liệu The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP phần 8 docx (Trang 63 - 68)

To find out whether an author has already been registered, you need to check the authors table to see whether any record matches the values submitted in the first_nameand family_namefields. In other words, you need to search the database (or in this case, a sin- gle table). If there’s a match, you need to stop the Insert Record server behavior from exe- cuting. Otherwise, the insert operation can go ahead. Since you don’t know what will be entered in the form fields, you need to pass their values as variables to the query that cre- ates the recordset.

If you are upgrading from a version of Dreamweaver earlier than Dreamweaver 8.0.2, pay careful attention to the instructions in this section, because the way you do this changed in a subtle but important way. Continue working with author_insert.php.

1.Open the Recordset dialog box in Advanced mode. Name the recordset checkAuthor, and select connAdminin the Connectionfield.

2.Expand Tablesin the Database itemsarea, expand the authorstable, select each of the columns in turn, and click SELECT. Highlight first_name, and click WHERE. Then do the same with family_name. You should now have a SQL query that looks like this:

SELECT authors.author_id, authors.first_name, authors.family_name FROM authors

WHERE authors.first_name AND authors.family_name

The WHEREexpression needs to search for the names entered in the first_name and family_namefields. Although you don’t know what the names will be, they will be stored in the $_POSTarray when the Insert authorbutton is clicked. Instead of entering the PHP variables directly in the SQL query, you need to define runtime variables in the Variables area in the center of the Recordset dialog box.

Dreamweaver replaces these variables with PHP format specifiers (normally %sor

%d) and uses the GetSQLValueString()function (see “Inspecting the server behav- ior code” in Chapter 15) to handle quotes and other characters that might cause problems with the SQL query. It also automatically adds quotes around text values.

This is an important difference from standard SQL.

The runtime variables are not PHP variables, so they shouldn’t begin with a dollar sign. You can use any alphanumeric characters to create the variables, as long as they don’t clash with the names of columns or any other part of the SQL query. I normally call the runtime variables var1, var2, and so on, but another common convention is to use col1,col2, and so on.

3.I’m going to use var1and var2as my runtime variables, so change the last line of the SQL query like this:

WHERE authors.first_name = var1 AND authors.family_name = var2 Dreamweaver uses these variables to prevent SQL injection, which exploits poorly written scripts to inject spurious code into SQL queries. SQL injection can be used to gain unauthorized access to a database and even wipe out all the stored data. In 2007, Adobe made significant changes to the way runtime vari- ables are handled. If you have pages created in Dreamweaver 8.0.1 or earlier that have SQL queries with runtime variables, you need to remove the PHP code completely and apply the server behavior again. The code is incompatible with Dreamweaver CS4.

Passing form values to a SQL query

4.You now need to define the runtime variables. Click the plus button alongside the Variableslabel in the Recordsetdialog box. This opens the Add Variabledialog box, which has the following four fields:

Name: This is the name of the runtime variable you want to define.

Type: This is a drop-down menu with four options: Integer, Text, Date, and Floating point number. Integer and Text are self-explanatory. The Date option doesn’t have any practical use in PHP, so you can ignore it. Floating point number accepts numbers with or without a decimal fraction. (In Dreamweaver 8.0.2 and CS3, Integerand Floating point numberwere called Numericand Double, respec- tively. The change in names is for clarity only; it doesn’t affect the code gener- ated by Dreamweaver.)

Default value: As you’ll see in the next chapter, Dreamweaver handles this value in an unexpected way. The only time it’s used is when you click the Testbutton in the Recordsetdialog box or when the page first loads. You must enter a value in this field, because Dreamweaver uses it to prevent a MySQL error if the vari- able defined as Runtime valuedoesn’t exist. Unless you want to display a default recordset result when a page first loads, set this to -1or anything that produces no results.

Runtime value: This is the value you want the runtime variable to represent when the SQL query is submitted.

16

5.When the form is submitted, you want var1 to use the value in the first_namefield, so set Runtime value to $_POST['first_name']. Unless you want to check the SQL with the Testbutton, enter anything in the Default value field. Here are the settings that I used:

PHP is case-sensitive, so make sure $_POSTis all uppercase. Click OK.

6.Define var2 in the same way, using

$_POST['family_name']as Runtime value. The

central section of the Recordsetdialog box should look like this:

7.Click OKto close the Recordsetdialog box, and save author_insert.php. You can check your code againstauthor_insert_02.php.

The recordset you created in the preceding section checks whether there’s already an author of the same name registered in the table. Unfortunately, Dreamweaver puts the code for a recordset immediately above the DOCTYPEdeclaration, so it’s afterthe Insert Record server behavior. I know what you’re thinking, but it doesn’t matter which order you enter them. Dreamweaver always puts recordsets beneath Insert Record and Update Record server behaviors, so you need to move it manually.

1.Open Code view. Locate the section of code in the following screenshot:

Preventing duplicate entries

This is the code for the checkAuthorrecordset. You can easily identify it, because the first line begins with $var1_checkAuthor, which is the way Dreamweaver defines var1, which you created in step 5 of the previous section. The part of the code that interacts with the database begins with mysql_select_dbon line 63 and continues to the end of the line that reads as follows:

$totalRows_checkAuthor = mysql_num_rows($checkAuthor);

As I explained in the previous chapter, $totalRows_recordsetNametells you how many records were retrieved by the recordset. So, you can use $totalRows_checkAuthorto determine whether a record already exists for the same author. If the number of rows is zero, there are no matching records, and you can safely insert the new author. But if any matching records are found, you know it’s a duplicate, so you need to skip the insert operation and display a warning.

2.Highlight the code shown on lines 55–67 in the screenshot, and cut them to the clipboard.

3.Scroll up about 17 lines, and paste the recordset in the position indicated here:

4.Make sure your cursor is at the end of the code you have just pasted, and press Enter/Return to make room to insert the following code highlighted in bold:

$totalRows_checkAuthor = mysql_num_rows($checkAuthor);

// assume that no match has been found

$alreadyRegistered = false;

// check whether recordset found any matches if ($totalRows_checkAuthor > 0) {

// if found, reset $alreadyRegistered

$alreadyRegistered = true;

} else {

// go ahead with server behavior

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {

5.Position your cursor right at the end of the code shown on line 39 in the previous screenshot (it should now be around line 61). This is the beginning of the Insert Record server behavior. Click the Balance Bracesbutton on the Codingtoolbar (or press Ctrl+’/Cmd+’) to find the end of the server behavior, and insert a closing brace (}) to match the opening one of the elseblock at the end of the code in step 4.

This prevents the Insert Record server behavior from running if a matching record is found in the authorstable.

6.All that remains now is to display a warning message if the insert is abandoned.

Scroll down until you find the following code (around line 87):

<h1>Insert new author</h1>

7.Add the following code immediately after it:

<?php

if ($_POST && $alreadyRegistered) {

echo '<p class="warning">'.$_POST['first_name'].' '. ➥

$_POST['family_name'].' is already registered</p>';

}

?>

This section of code will run only if the $_POSTarray contains any values (in other words, the insert form has been submitted) and if $alreadyRegisteredhas been set to true.

8.Save the page, and preview it in a browser. Try inserting a name that you know already exists in the table, such as William Shakespeare. You should see a warning that William Shakespeare is already registered.

Note that falseand truein this code block are keywords. They must not be enclosed in quotes.

16

Then try a name you know hasn’t been registered. You’ll see a warning that author_list.phpwasn’t found (you haven’t created it yet), but when you reload quote_insert.php, the new name should be listed in the drop-down menu of authors’ names. Check your code against author_insert_03.phpif you have any problems.

Một phần của tài liệu The Essential Guide to Dreamweaver CS4 with CSS, Ajax, and PHP phần 8 docx (Trang 63 - 68)

Tải bản đầy đủ (PDF)

(94 trang)