patrimatic Posted February 27, 2011 Share Posted February 27, 2011 I want my PHP code to display and handle a form. If the form hasn't been submitted it needs to display the form. If the form has been submitted but the data couldn't be validated then I want to display the same form (with the user's data intact). If the form has been submitted and the data was validated then it handles the form and prints a message. The problem I seem to be having is that I have nested conditionals that both need to execute the same code. I cant seem to wrap my head around it. Quote Link to comment https://forums.phpfreaks.com/topic/228979-logic-question-with-a-form/ Share on other sites More sharing options...
PFMaBiSmAd Posted February 27, 2011 Share Posted February 27, 2011 Form/form processing pseudo code - // form processing code if(form_submitted){ validate form data if(no form_errors){ // use form data } } // form code if(form_not_submitted OR form_errors){ if(form_errors){ display form errors } display form with existing field values (if present) } Example Form/form processing code - <?php // form processing code if($_SERVER['REQUEST_METHOD'] == "POST"){ //validate form data $form_errors = array(); // define array to hold form errors if($_POST['username'] == ''){ $form_errors[] = 'No username supplied!'; } if($_POST['password'] == ''){ $form_errors[] = 'No password supplied!'; } else { // further password validation if(strlen($_POST['password']) < 5){ $form_errors[] = "Password length must be at least 5 characters!"; } } if(empty($form_errors)){ // use form data echo "Thank you for submitting your data, " . htmlentities($_POST['username'],ENT_QUOTES) . ".<br />"; } } // form code if($_SERVER['REQUEST_METHOD'] != "POST" || !empty($form_errors)){ if(!empty($form_errors)){ //display form errors echo "Please correct the following form errors -<br />"; foreach($form_errors as $error){ echo "$error<br />"; } } //display form with existing field values (if present) ?> <form method='post' action=''> <label for="username">Username:</label> <input type='text' id='username' name='username' value='<?php echo isset($_POST['username']) ? htmlentities($_POST['username'],ENT_QUOTES) : ''?>'> <br /> <label for="password">Password:</label> <input type='password' id='password' name='password' value='<?php echo isset($_POST['password']) ? htmlentities($_POST['password'],ENT_QUOTES) : ''?>'> <br /> <input type='submit'> </form> <?php } ?> Quote Link to comment https://forums.phpfreaks.com/topic/228979-logic-question-with-a-form/#findComment-1180219 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.