When your web application contains multiple controls, and you must tell the user there's a problem with the data in one of them, it's considerate if you preserve the data in the others if it checked out OK. For example, phprestore.php, Example 6-15, asks for the user's first name and last name. If the user omits one name, the web page still displays the name that the user entered, so no retyping is needed, but it also asks the user to add the missing data. Example 6-15. Preserving user-entered data, phprestore.php<HTML> <HEAD><TITLE>Preserving Data</TITLE></HEAD> <BODY> <CENTER><H1>Preserving Data</H1> <?php $errors = array(); if(isset($_REQUEST["seen_already"])){ validate_data(); if(count($errors) != 0){ display_errors(); display_welcome(); } else { process_data(); } } else { display_welcome(); } function validate_data() { global $errors; if($_REQUEST["FirstName"] == "") { $errors[] = "<FONT COLOR='RED'>Please enter your first name</FONT>"; } if($_REQUEST["LastName"] == "") { $errors[] = "<FONT COLOR='RED'>Please enter your last name</FONT>"; } } function display_errors() { global $errors; foreach ($errors as $err){ echo $err, "<BR>"; } } function process_data() { echo "Your first name is "; echo $_REQUEST["FirstName"]; echo "<BR>Your last name is "; echo $_REQUEST["LastName"]; } function display_welcome() { $first_name = isset($_REQUEST["FirstName"]) ? $_REQUEST["FirstName"] : ""; $last_name = isset($_REQUEST["LastName"]) ? $_REQUEST["LastName"] : ""; echo "<FORM METHOD='POST' ACTION='phprestore.php'>"; echo "What's your first name?"; echo "<INPUT NAME='FirstName' TYPE='TEXT' VALUE='", $first_name, "'>"; echo "<BR>"; echo "What's your last name?"; echo "<INPUT NAME='LastName' TYPE='TEXT' VALUE='", $last_name, "'>"; echo "<BR>"; echo "<INPUT TYPE='SUBMIT' VALUE='Submit'>"; echo "<INPUT TYPE='HIDDEN' NAME='seen_already' VALUE='hidden_data'>"; echo "</FORM>"; } ?> </CENTER></BODY> </HTML> You can see how this works in Figure 6-20, where the user omitted his last name, so we're asking him to fix it while still preserving the data he did enter. Cool. Figure 6-20. Preserving data despite errors. |