PHP SOLUTIONS: DYNAMIC WEB DESIGN (Kids web site) MADE EASY Making
PHP SOLUTIONS: DYNAMIC WEB DESIGN MADE EASY Making sure required fields aren t blank When required fields are left blank, you don t get the information you need, and the user may never get a reply, particularly if contact details have been omitted. PHP Solution 5-3: Checking required fields Continue using the same files. Alternatively, use contact04.php from the download files. The completed code for this section is in contact05.php. 1. Start by creating two arrays: one listing the name attribute of each field in the form and the other listing all required fields. Also, initialize an empty array to store the names of required fields that have not been completed. For the sake of this demonstration, make the email field optional, so that only the name and comments fields are required. Add the following code just before the section that processes the $_POST variables: $subject = ‘Feedback from Japan Journey site’; // list expected fields $expected = array(’name’, ‘email’, ‘comments’); // set required fields $required = array(’name’, ‘comments’); // create empty array for any missing fields $missing = array(); // process the $_POST variables 2. In PHP Solution 5-2, the $_POST variables were assigned manually to variables that use the same name as the $_POST array key. For example, $_POST[’email’] became $email. With three fields, manual assignment is fine, but it becomes a major chore if you have a dozen or more fields. Let s kill two birds with one stone by checking the required fields and automating the naming of the variables at the same time. Replace the three lines of code beneath the $_POST variables comment as follows: // process the $_POST variables foreach ($_POST as $key => $value) { // assign to temporary variable and strip whitespace if not an array $temp = is_array($value) ? $value : trim($value); // if empty and required, add to $missing array if (empty($temp) && in_array($key, $required)) { array_push($missing, $key); } // otherwise, assign to a variable of the same name as $key elseif (in_array($key, $expected)) { ${$key} = $temp; } } // build the message
Go visit our java server pages services for a reliable, lowcost webhost to satisfy all your needs.