Form Processing
Form processing under PHP is simple. Listing 5 and Figure 1 show an example of a form for adding a new entry to the address book. A simple table lines up the text-entry fields.
Listing 5. A script to create the form shown in Figure 1
|
The form in Listing 5 specifies the action add_handler.php3, which is shown in Listing 6.
Listing 6 introduces some new topics: form handling, adding new rows to a database, error handling, and redirecting.
The form contains three form elements in new.html : last_name, first_name, and email. To access the value the user entered as the last_name form element, the variable $last_name is used. In this example, I submit the form using the HTTP post method. Use the same technique when using get rather than post .
Line 7 of Listing 6 retrieves the value for the form element last_name, using the following logic:
- Use the empty function to determine if the user left the last name blank. If so, then set $last_name to "NULL" .
- Otherwise, use the addslashes function to add the appropriate backslashes for quotes in the last name and place the last name in double quotes. This prevents the script from submitting invalid SQL requests to MySQL.
Conditional syntax just like that found in C, Perl, and Java accomplishes the retrieval on lines 7 and 8. After processing the first name and e-mail data in the same manner, line 14 creates the SQL INSERT command to add the new entry to the database. There's no value for the ID column because the AUTO_INCREMENT feature of MySQL was used to create the PERSON table. The ID field automatically will have the next available integer.
Line 16 sends the INSERT command to the database. If the request is successful, it returns a positive value, and the user is redirected to the index page index.php3 , using the redirect function on line 19. (Note that the redirect function needs to be called before any HTML output is sent.) The redirect causes processing of this page to end, and an HTTP redirect header will be sent.
The script handles errors by saving the error message to the $error variable, using the mysql_error function, and then not performing the redirect. This allows the HTML at the end of the script to be displayed. In the event of an error, lines 28 through 30 cause the display of an error message and the SQL command that caused the problem.
The downloadable version of the code example (see Resources) includes some additional pages (editing and deleting entries). They do not introduce any additional concepts, so they aren't included here in the article.
Listing 6. Processing a submitted form
|
View Script Web databases quickly with PHP Discussion
Page: 1 2 3 4 5 6 7 8 Next Page: Maintaining Sessions