PHP

Saving last-entered values as a session variable

We now develop the script to pass the field data from the validation script back to the client entry <form> to avoid rekeying when an error occurs. The script is modified by saving the user-entered data in another session variable, the associative array $formVars. The client details <form> already uses an array, $formVars, to populate the entry fields from a customer record when editing an existing client. By setting the $formVars session variable in the validation script, the client entry <form> populates the <input> fields with the values that were last entered.

The following code-inserted just after $errors is registered as a session variable-registers the array $formVars and then loops through each user-entered variable, setting a value in the array, indexed by the name of the variable. Note that the clean( ) function described in Chapter 5 is used to secure the user data.

// Set up a $formVars array with the POST variables
// and register with the session.
if (!session_is_registered("formVars"))
   session_register("formVars");
foreach($HTTP_POST_VARS as $varname => $value)
    $formVars[$varname] = trim(clean($value, 50));

When the modified client entry <form> is run, the most recent values entered from the session variable $formVars are shown.

While the $HTTP_POST_VARS associative array can be stored in a session and accessed like any other session variable, there is a catch. The value of $HTTP_POST_VARS is determined by PHP before scripts are run. If a session has registered a variable with the name $HTTP_POST_VARS, the values held in $HTTP_POST_VARS that were set up by PHP-as a result of processing a POST request-are overwritten by the session variable.

If register_globals is enabled in php.ini, the GET or POST variables PHP sets up can also be overwritten by session variables with the same name.

The safe way to read cookies, GET, and POST variables that have name conflicts is to use the $HTTP_COOKIE_VARS, $HTTP_GET_VARS, and $HTTP_POST_VARS associative arrays, as discussed in Chapter 6.

The final change needed in Example 6-8 is to destroy the session when the script successfully saved a row in the customer table:

// Clear the session
session_destroy(  );
The final validation script

Example 8-4 shows the final validation script derived from Example 6-8.

Example 8-4. The complete validation script derived from Example 6-8
<?php
  include 'db.inc';
  include 'error.inc';
  // Initialize a session
  session_start(  );
  // Register an error array - just in case!
  if (!session_is_registered("errors"))
     session_register("errors");
  // Clear any errors that might have been
  // found previously
  $errors = array(  );
  // Set up a $formVars array with the POST variables
  // and register with the session.
  if (!session_is_registered("formVars"))
     session_register("formVars");
  foreach($HTTP_POST_VARS as $varname => $value)
      $formVars[$varname] = trim(clean($value, 50));
  // Vaildate the firstName
  if (empty($formVars["firstName"]))
      // First name cannot be a null string
      $errors["firstName"] =
          "The first name field cannot be blank.";
  // Validate the Surname
  if (empty($formVars["surname"]))
      // the user's surname cannot be a null string
      $errors["surname"] =
          "The surname field cannot be blank.";
  // Validate the Address
  if (empty($formVars["address1"]))
      // all the fields of the address cannot be null
      $errors["address"] =
          "You must supply at least one address line.";
  // Validate the City
  if (empty($formVars["city"]))
      // the user's city cannot be a null string
      $errors["city"] = "You must supply a city.";
  // Validate Date of Birth
  if (empty($formVars["dob"]))
      // the user's date of birth cannot be a
      // null string
      $errors["dob"] =
        "You must supply a date of birth.";
  elseif (!ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})$",
          $formVars["dob"],
          $parts))
      // Check the format
      $errors["dob"] =
        "The date of birth is not a valid date " .
        "in the format DD/MM/YYYY";
  if (empty($formVars["email"]))
      // the user's email cannot be a null string
      $errors["email"] =
        "You must supply an email address.";
  // Now the script has finished the validation,
  // check if there were any errors
  if (count($errors))
  {
      // There are errors.  Relocate back to the
      // client form
      header("Location: example.8-5.php");
      exit;
  }
  // If we made it here, then the data is valid
  if (!($connection = @ mysql_pconnect($hostName,
                                       $username,
                                       $password)))
     showerror(  );
  if (!mysql_select_db($databaseName, $connection))
     showerror(  );
  // Reassemble the date of birth into database format
  $dob = " \"$parts[3]-$parts[2]-$parts[1]\"";
  // Is this an update?
  if (!empty($custID))
  {
    $query = "UPDATE customer SET ".
      "surname = \"" . $formVars["surname"] . "\", " .
      "firstname = \"" . $formVars["firstName"] . "\", " .
      "addressline1 = \"" .
                    $formVars["address1"] . "\", " .
      "city = \"" . $formVars["city"] . "\", " .
      "email = \"" . $formVars["email"] . "\", " .
      "birth_date = " . $dob .
      " WHERE cust_id = $custID";
  }
  else
     // Create a query to insert the customer
     $query = "INSERT INTO customer SET" .
       "cust_id = NULL, " .
       "surname = \"" . $formVars["surname"] . "\", " .
       "firstname = \"" .
                    $formVars["firstName"] . "\", " .
       "addressline1 = \"" .
                    $formVars["address1"] . "\", " .
       "city = \"" . $formVars["city"] . "\", " .
       "email = \"" . $formVars["email"] . "\", " .
       "birth_date = $dob";
  // Run the query on the customer table
  if (!(@ mysql_query ($query, $connection)))
     showerror(  );
  // Is this an insert?
  if (empty($custID))
  // Find out the cust_id of the new customer
  $custID = mysql_insert_id(  );
  // Clear the session
  session_destroy(  );
  // Now show the customer receipt
  header("Location: customer_receipt.php?custID=$custID");
?>

The Client Entry <form> Script

Now let's turn to the changes required for the script that generates the client entry <form> shown in Example 6-7. In the last section, we set up two session variables: the associative array $errors used to hold a list of error messages found in the validation script and the associative array $formVars used to hold the POST variables you processed.

Displaying previously entered values

As Example 6-7 already sets the value attribute of the <input> elements from the array $formVars, there are no changes needed to display previously entered values; Example 6-7 uses $formVars when displaying the current values of clients from the customer table. By setting $formVars as a session variable, Example 6-7 displays the values passed back from the validation script with each <input> field.

by BrainBellupdated
Advertisement: