AlexBeau Posted July 23, 2011 Share Posted July 23, 2011 Was doing the last section of chapter 7 where you take array data from a HTML and print it back out on the screen. The script is event.php. Larry mentioned that in the real world you would use validation to make sure that a event name has been entered into the form. I gave it a shot and this is what I have come up with: <?php // Filename: event.php // Author: Alex Beauchamp // Date: 7/23/11 // This script creates an array from an html form's group of checkboxes // Error Management ini_set('display_errors', 1); error_reporting(E_ALL | E_STRICT); // Create flag variable for validation $okay = TRUE; // Validate that event name is entered, if not print error message if (empty($_POST['name'])) { print '<p class="error">Please enter a name for your event.</p>'; $okay = FALSE; } // Validate that at least 1 day is selected if (isset($_POST['days']) AND is_array($_POST['days'])) { foreach ($_POST['days'] as $day) { $selected[] = $day; $selected_days = implode(', ', $selected); } } else { // Print error message if no weekday is selected print '<p class="error">Please select at least one day for your event.</p>'; $okay = FALSE; } // If name and day okay print event details if ($okay) { print "<p>You want to add an event called <span class=\"bold\">{$_POST['name']}</span> which takes place on: <br />"; print $selected_days; } ?> Would this be the correct way to going about validating the inputs and then printing them if correct or warning if they are not correct? If not is there a better way to do it? Thank you, Alex Link to comment Share on other sites More sharing options...
Antonio Conte Posted July 25, 2011 Share Posted July 25, 2011 The way Larry does this is to check whether the array are empty of not. If it's not empty, that would mean an error has occurred. My thinking is that a textual description of the error is what's important. That is also how Larry does it. (No wonder I concur, right) // Create the array. It's now empty $errors = array(); if (isset($something)) { // it does exist } else { // it does NOT exist $errors[] = "variable Something is empty"; } // Check array and foreach it to get possible errors if (empty($errors) { // Errors array are empty. Rock on with anything... } else { foreach ($errors as $error_message) { echo $message; // looks like someone fucked up } } Link to comment Share on other sites More sharing options...
Recommended Posts