dmacman Posted March 5, 2008 Share Posted March 5, 2008 Hi Everyone, I am not an expert in functions, and I am stuck trying to convert some procedural code to a function. I have this error code. $errors = array(); // initialize to empty array if(!isset($_POST['FirstName']) or trim($_POST['FirstName'] === '')) { $errors['FirstName'] = '"First Name" is a required field.'; } if(!isset($_POST['LastName']) or trim($_POST['LastName'] === '')) { $errors['LastName'] = '"Last Name" is a required field.'; } //etc...... ...and I tried to write it as a function, but I know this is not correct. $errors = array(); // initialize to empty array function errors($string, $phrase){ if(!isset($string) or trim($string === '')) { $errors[$string] = $phrase ; } return $errors[$string]; } $firstname = errors($_POST['FirstName'], '"First Name" is a required field, please correct this entry.'); $lastname = errors($_POST['LastName'], '"Last Name" required field, please correct this entry.'); I know this is wrong, because it test for the POST instead of assigning the variables to the function (I think). But I am stuck on how to loop the if(!isset($string) or trim($string === '')) into the function. I would appreciate any guidance or suggestions. Thanks in advance, Don Quote Link to comment Share on other sites More sharing options...
craygo Posted March 5, 2008 Share Posted March 5, 2008 you set the array outside the function so it may not work. Also you need 2 parts. One if it passes and one if it fails. try something like this <?php function errors($string, $phrase){ $errors = array(); // initialize to empty array if(!isset($string) or trim($string === '')) { $errors[$string] = $phrase; } else { $errors[$string] = $string; } return $errors[$string]; } $firstname = errors($_POST['FirstName'], '"First Name" is a required field, please correct this entry.'); $lastname = errors($_POST['LastName'], '"Last Name" required field, please correct this entry.'); ?> Now if all is well you will get back the first or last name, if it fails you will get your error message. ray Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 5, 2008 Share Posted March 5, 2008 Use the following instead: <?php $displayForm = true; if(isset($_POST['submit'])) { $displayForm = false; $errors = null; function fieldCheck($field_name, $error_message) { global $errors; if(!isset($_POST[$field_name]) || ( trim($_POST[$field_name]) == '') ) { $errors[$field_name] = '<span style="color: #F00; font-weight: bold">' . $error_message . '</span><br />'; } } $firstname = fieldCheck('FirstName', 'Please enter your firstname'); $lastname = fieldCheck('LastName', 'Please enter your lastname'); if(is_array($errors)) { $displayForm = true; } } if($displayForm) { ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <?php echo (isset($errors['FirstName'])) ? $errors['FirstName'] : null; ?> Firstname: <input type="text" name="FirstName" value="<?php echo (isset($_POST['FirstName'])) ? $_POST['FirstName'] : null; ?>"/><br /> <?php echo (isset($errors['LastName'])) ? $errors['LastName'] : null; ?> Lastname: <input type="text" name="LastName" value="<?php echo (isset($_POST['LastName'])) ? $_POST['LastName'] : null; ?>" /><br /> <input type="submit" name="submit" value="POST" /> </form> <?php } else { echo 'Firstname: ' . $_POST['FirstName'] . '<br />'; echo 'Lastname: ' . $_POST['LastName']; } ?> Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 6, 2008 Author Share Posted March 6, 2008 OK, thanks to both of you for helping. If I use craygo's method. I get... No errors and the form moves on to page 2, unless I assign at least on variable to the array like so. $title = errors('Title', 'This is a required field.'); $errors[0] = $title; Then it works. Except, when I echo the variable $title to tell them what they missed, it gives me the key, not the error value (IE, it prints 'Title' not 'This is a required field.') Now if I use wildteen88's method, I get... If I echo $errors['Title'] I get the error message, but I noticed that if I do a print_r($errors), I get this for Title... $errors Array Array ( [Title] => This is a required field. [This is a required field.This is a required field.] => This is a required field. [] => This is a required field. ) Isn't that a strange result for Title? I was expecting just. [Title] => This is a required field. I appreciate your feedbakc and help, Don Quote Link to comment Share on other sites More sharing options...
craygo Posted March 6, 2008 Share Posted March 6, 2008 [code]well just return $error then it will be an array. Here is the code i used <?php $_POST['FirstName'] = "Ray"; $_POST['LastName'] = ""; function errors($string, $phrase){ $errors = array(); // initialize to empty array if(!isset($string) or trim($string === '')) { $errors[$string] = $phrase; } else { $errors[$string] = $string; } return $errors[$string]; } $firstname = errors($_POST['FirstName'], '"First Name" is a required field, please correct this entry.'); $lastname = errors($_POST['LastName'], '"Last Name" required field, please correct this entry.'); echo $firstname."<br />"; //Result is Ray echo $lastname; //Result is "Last Name" required field, please correct this entry. ?>[/code] Is that what you were looking to get back?? Ray Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 6, 2008 Author Share Posted March 6, 2008 Yes, thats what I am trying to do. So if there is an error (in this case $lastname) it prints. My page code (logic is as follows). if(isset($_POST['form1_submit'])) { require 'form1_processor.php'; // process input from Form #1 include("errors.php"); if(count($errors) == 0) // no errors { require 'form2.php'; // displays Form #2 } else { require 'form1.php'; // re-displays Form #1 } } elseif(isset($_POST['form2_submit'])) { require 'form2_processor.php'; // processes data from Form #2 if(count($errors) == 0) { include("vote.php"); header('Location: success.php'); // all done exit; } else { require 'form2.php'; // re-display Form #2 } } else { require 'form1.php'; // display Form #1 } So, the form I am on now (form1_submit) has all the user data. First Name Last Name etc. and you can see why I am trying to stay with the $errors array so it there is a value, it wont pass this test "if(count($errors) == 0)" and move on to page 2 of the form. Make sense? This way, I can have all my data on one page, and just include my forms, and keep my POST data and not lose it and have to deal with POST errors and having to use Javascript validation between multi-page forms. So with all that explained, how do I move on with your solution? Don Quote Link to comment Share on other sites More sharing options...
craygo Posted March 6, 2008 Share Posted March 6, 2008 well instead of using $lastname we will put them in an array for you The function will now be. <?php function errors($string, $phrase){ $errors = array(); // initialize to empty array if(!isset($string) or trim($string === '')) { return $phrase; } else { return false; } } ?> And now you can use a loop to check the POST variables <?php $errors = array(); foreach($_POST as $key => $val){ if(errors($val, "\"$key\" is a required field, please correct this entry.")){ $errors[] = errors($_POST['LastName'], '"Last Name" required field, please correct this entry.'); } } ?> So now you can use if(count($errors) == "0"){ Ray Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 6, 2008 Author Share Posted March 6, 2008 Hi Ray, So I did like you suggested. $errors = array(); foreach($_POST as $key => $val){ if(errors($val, "\"$key\" is a required field, please correct this entry.")){ $errors[] = errors($_POST['Title'], '"Title" required field, please correct this entry.'); $errors[] = errors($_POST['FirstName'], '"First Name" required field, please correct this entry.'); //etc } } End it I print_R($errors) I get ... $errors Array Array ( [0] => "Title" required field, please correct this entry. [1] => "First Name" required field, please correct this entry. [2] => //etc ..... ..... [13] => "Rating" required field, please correct this entry. [14] => "Title" required field, please correct this entry. // list starts over here <---------------------- [15] => "First Name" required field, please correct this entry. and repeats up to 349 ???? Why? Also, doing it this way, what to I echo $errors['Title'] wont work, so I would have to echo $errors[0] correct? Don Quote Link to comment Share on other sites More sharing options...
craygo Posted March 6, 2008 Share Posted March 6, 2008 Since you are in a loop and giving aliases to the POST values you only need to check the values once $errors = array(); foreach($_POST as $key => $val){ if(errors($val, "\"$key\" is a required field, please correct this entry.")){ $errors[$key] = errors($val, '"'.$key.'" required field, please correct this entry.'); } } now you could echo $errors['FirstName'] How many values do you have being passed. Ray Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 6, 2008 Author Share Posted March 6, 2008 I have 24 instances of the FirstName value. (actually, 24 of all of them) [1] => "First Name" thru [337] => "First Name" And if i echo $errors['FirstName'] I do not get anything. If I change the loop to ... $errors['FirstName'] = errors($_POST['FirstName'], '"First Name" required field, please correct this entry.'); and then echo errors['FirstName']l it works. Don Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 6, 2008 Share Posted March 6, 2008 Are you defining your errors for each field within the foreach loop? If so you should not be doing that. The loop will automatically define an error message for you if the errors() function returns true if the field is empty. If you want to define different error messages for each field then I'd recommend you to setup an array of error messages for each field, then within the foreach loop check to see if you have defined an error message for that particular field. Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 6, 2008 Author Share Posted March 6, 2008 I am defining the them in the loop. $errors = array(); foreach($_POST as $key => $val){ if(errors($val, "\"$key\" is a required field, please correct this entry.")){ $errors['Title'] = errors($_POST['Title'], '"Title" required field, please correct this entry.'); $errors['FirstName'] = errors($_POST['FirstName'], '"First Name" required field, please correct this entry.'); $errors['Lastname'] = errors($_POST['LastName'], '"Last Name" required field, please correct this entry.'); $errors['Position'] = errors($_POST['Position'], '"Position" required field, please correct this entry.'); $errors['GRADE'] = errors($_POST['GRADE'], '"Grade" required field, please correct this entry.'); $errors['SubjectTaught'] = errors($_POST['SubjectTaught'], '"Subject Taught" required field, please correct this entry.'); $errors['School'] = errors($_POST['School'], '"School" required field, please correct this entry.'); $errors['SchoolAddress1'] = errors($_POST['SchoolAddress1'], '"School Address 1" required field, please correct this entry.'); $errors['SchoolAddress2'] = errors($_POST['SchoolAddress2'], '"School Address 2" required field, please correct this entry.'); $errors['City'] = errors($_POST['City'], '"City" required field, please correct this entry.'); $errors['State'] = errors($_POST['State'], '"State" required field, please correct this entry.'); $errors['Zip'] = errors($_POST['Zip'], '"Zip" required field, please correct this entry.'); $errors['PrimaryEmailAddress'] = errors($_POST['PrimaryEmailAddress'], '"Primary Email Address" required field, please correct this entry.'); $errors['Rating'] = errors($_POST['Rating'], '"Rating" required field, please correct this entry.'); } } And I think I follow what you are saying and I 'think' thats what I am trying to get to, but don't know how to change my function and or code the array to work with it. Can you guide me on this? Thanks in advance, Don Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 6, 2008 Share Posted March 6, 2008 You dont need to do that The foreach loop will do it for you. It dynamically checks the field for you $errors = array(); foreach($_POST as $key => $val){ if(errors($val, "\"$key\" is a required field, please correct this entry.")){ $errors[$key] = errors($val, '"'.$key.'" required field, please correct this entry.'); } } echo '<pre>' . print_r($errors, true) . '</pre>'; Run the above code without modifying the foreach loop and admire the results. if you are unsure how foreach works the have a read of the manual. Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 7, 2008 Author Share Posted March 7, 2008 Yes, you hit it right on the head. Thanks that worked great! If you don't mind, I had another function/test that I cannot seem to resolve which is right along the same line. I have a dynamic function checkbox code, that works, except it doesn't seem to get the POST data for 'checked' so when they come back, like when they do not fill in the data like above, the checkboxes are always reset. Here is my code. $grades = array('K-3', '4', '5', '6', '7', '8', '9', '10', '11', '12', 'Other'); $x='5'; //tabindex value $zz='0'; foreach($grades as $grade) { $selected = ((isset($_POST['grade']) && !empty($_POST['grade'])) ? in_array($grade, $_POST['grade']) : false); echo '<input type="checkbox" id="chk" name="GRADE['.$zz.']" tabindex="'.$x.'" value="GRADE ' . $grade . '"' . ($selected ? 'checked' : '') . '>'; if($grade=='Other') { echo ' <label for="' . $grade . '_chckbx">' . $grade .' '; } else { echo ' <label for="' . $grade . '_chckbx">' . $grade . ' |'; } $x++; $zz++; } The HTML result of the above is (to save you from putting in your editor). <input type="checkbox" id="chk" name="GRADE[0]" tabindex="5" value="GRADE K-3"> <label for="K-3_chckbx">K-3 |<input type="checkbox" id="chk" name="GRADE[1]" tabindex="6" value="GRADE 4"> <label for="4_chckbx">4 |<input type="checkbox" id="chk" name="GRADE[2]" tabindex="7" value="GRADE 5"> <label for="5_chckbx">5 |<input type="checkbox" id="chk" name="GRADE[3]" tabindex="8" value="GRADE 6"> <label for="6_chckbx">6 |<input type="checkbox" id="chk" name="GRADE[4]" tabindex="9" value="GRADE 7"> <label for="7_chckbx">7 |<input type="checkbox" id="chk" name="GRADE[5]" tabindex="10" value="GRADE 8"> <label for="8_chckbx">8 |<input type="checkbox" id="chk" name="GRADE[6]" tabindex="11" value="GRADE 9"> <label for="9_chckbx">9 |<input type="checkbox" id="chk" name="GRADE[7]" tabindex="12" value="GRADE 10"> <label for="10_chckbx">10 |<input type="checkbox" id="chk" name="GRADE[8]" tabindex="13" value="GRADE 11"> <label for="11_chckbx">11 |<input type="checkbox" id="chk" name="GRADE[9]" tabindex="14" value="GRADE 12"> <label for="12_chckbx">12 |<input type="checkbox" id="chk" name="GRADE[10]" tabindex="15" value="GRADE Other"> <label for="Other_chckbx">Other What did I miss? I posted this on another forum and they were stumped? Thoughts? Thanks, Don Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 7, 2008 Author Share Posted March 7, 2008 For the last POST, I should mention, if I chose K-3 and 4, and did a print_r, I would get. [grade] => Array ( [ 0] => GRADE K-3 [1] => GRADE 4 ) Also, with the new function, I now get ( I am assuming its the checkbox arrays, since I have 2 sets of them and I am getting 2 errors). Warning: Illegal offset type in D:\Program Files\Apache Group\Apache2\htdocs\izzit\feedback\errors.php on line 16 Warning: Illegal offset type in D:\Program Files\Apache Group\Apache2\htdocs\izzit\feedback\errors.php on line 16 and line 16 of the function is. return $errors[$string]; So to condense, I have 2 issues, the checkboxes not retaining there checked state, and them causing the Illegal offest. I found this comment on http://www.php.net/manual/en/language.types.array.php about arrays. Using TRUE as a key will evaluate to integer 1 as key. Using FALSE as a key will evaluate to integer 0 as key. Using NULL as a key will evaluate to the empty string. Using the empty string as key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets. You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type. So will this still work for the checkboxes, and can we fix it and make them retain their checked states when we come back to fix the errors? Don Quote Link to comment Share on other sites More sharing options...
dmacman Posted March 7, 2008 Author Share Posted March 7, 2008 One other thing, does this new way of doing a foreach with the POST data automatically make all POST data an error if not filled out? Because, if so, thats going to cause a problem with my code, since not all the fields are required and my page code, is going to fail if they do not fill out all the fields. thanks, Don Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted March 7, 2008 Share Posted March 7, 2008 You can setup an array of fields which are required and then within the foreach use in_array to see if the current field requires validation, example: // list require field name within the array $required_fields = array('FirstName', 'LastName'); $errors = array(); foreach($_POST as $fieldName => $fieldValue) { if(in_array($fieldName, $required_fields)) { if(errors($fieldValue, "\"$fieldName\" is a required field, please correct this entry.")) { $errors[$fieldName] = errors($fieldValue, '"'.$fieldName.'" required field, please correct this entry.'); } } } echo '<pre>' . print_r($errors, true) . '</pre>'; Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.