anthonyJ Posted November 14, 2014 Share Posted November 14, 2014 (edited) My problem is when the entries in the form are validated and some fields with incorrect entries are found the fields filled out stay on the re-load of the form, all of them except the US States drop down menu which reverts back to Alabama every time. I would like to see that the user selection stays in place even after a re-load of the form. and with my limited experience I am having an issue trying to figure this out for a school project. Any help at all would be greatly appreciated, like what variables to create/call on and where exactly I insert this code. Much appreciated. here is the display code: <?php /* Program name: exercise_4_form.inc * Description: Defines a form that collects a user's * name and mailing address. */ $rows = array( "first_name" => "First Name (optional)", "last_name" => "Last Name", "phone" => "Phone Number", "city" => "City", "state" => "State", "address" => "Address", "zip_code" => "ZIP Code", "e_mail" => "E-Mail"); $states_list = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona", 'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut", 'DE'=>"Delaware",'DC'=>"District Of Columbia",'FL'=>"Florida",'GA'=>"Georgia", 'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine", 'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota", 'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska", 'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico", 'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio", 'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island", 'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas", 'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia", 'WI'=>"Wisconsin",'WY'=>"Wyoming"); $submit = "Submit mailing information"; ?> <html> <head> <style type='text/css'> <!-- body { background: #42413C; color: #000; font-family: Tahoma, Geneva, sans-serif; font-size: 90%; } form { margin: 1em 2 2 2; padding: 1; width: 1100px; margin-left: 35%; } .field {padding-bottom: 1em; } label { font-weight: bold; float: left; width: 15%; margin-right: 1em; text-align: right; background-color: #9F6; padding-right: 5px; } select {margin-bottom: 1em;} #submit { margin-left: 15%; } h3 { width: 500px; margin-left: 35%; } --> </style> </head> <body> <h3>Please enter your mailing information below:</h3> <?php /* loop that displays the form */ echo "<form action='$_SERVER[PHP_SELF]' method='POST'>"; foreach($rows as $field => $label) if($field == "state") { echo "<label for='$field'>$label</label> <select id='$field' name='$field'>\n"; foreach ( $states_list as $abbr => $sname ) { echo "<option value='$abbr'>$sname</option>\n"; } echo "</select>\n"; } else { echo "<div class='field'><label for='$field'>$label</label> <input id='$field' name='$field' type='text' value='".@$$field."' size='25%' maxlength='65' /></div>\n"; } echo "<div id='submit'> <input type='hidden' name='submitted' value='yes'> <input type='submit' value='$submit'></div>"; ?> </form> </body> </html>Here is the Logic on the combined php file that displays and has the statements on it for the form: <?php /* Program name: exercise_4_form_verifications.php * Description: Program checks all the form fields for * blank fields and verifies them */ if(isset($_POST['submitted']) and $_POST['submitted'] == "yes") { foreach($_POST as $field => $value) { if(empty($value)) { if($field != "first_name") { $blank_array[] = $field; } } else { $good_data[$field] = strip_tags(trim($value)); } } if(@sizeof($blank_array) > 0) { $message = "<p style='color: black; margin-bottom: 0;font-weight: bold; margin-left: 35%'> You didn't fill in one or more required fields. You must enter: <ul style='color: yellow; margin-top: 0; margin-left: 35%; list-style: none' >"; foreach($blank_array as $value) { $message .= "<li>$value</li>"; } $message .= "</ul>"; echo $message; extract($good_data); include("exercise_4_form.inc"); exit(); } foreach($_POST as $field => $value) { if(!empty($value)) { $name_verify = "/^[A-Za-z' -]{1,50}$/"; $phone_verify = "/^[0-9)(xX -]{7,20}$/"; $city_verify = "/^[A-Za-z' -]{1,50}$/"; $address_verify = "/^[A-Za-z0-9 .,'-]{1,50}$/"; $zip_verify = "/^[0-9]{5}(\-[0-9]{4})?$/"; $e_mail_verify = "/^.+@.+\\..+$/"; if(preg_match("/last/i",$field)) { if(!preg_match($name_verify,$value)) { $error_array[] = "$value is not a valid last name"; } } if(preg_match("/phone/i",$field)) { if(!preg_match($phone_verify,$value)) { $error_array[] = "$value is not a valid phone number"; } } // endif phone format check if(preg_match("/city/i",$field)) { if(!preg_match($city_verify,$value)) { $error_array[] = "$value is not a valid city"; } } if(preg_match("/address/i",$field)) { if(!preg_match($address_verify,$value)) { $error_array[] = "$value is not a valid address"; } } if(preg_match("/zip/i",$field)) { if(!preg_match($zip_verify,$value)) { $error_array[] = "$value is not a valid ZIP code"; } } if(preg_match("/e_mail/i",$field)) { if(!preg_match($e_mail_verify,$value)) { $error_array[] = "$value is not a valid e-mail address"; } } } $clean_data[$field] = strip_tags(trim($value)); } if(@sizeof($error_array) > 0) { $message = "<ul style='color: yellow; margin-top: 0; margin-left: 35%; list-style: none' >"; foreach($error_array as $value) { $message .= "<li>$value</li>"; } $message .= "</ul>"; echo $message; extract($clean_data); include("exercise_4_form.inc"); exit(); } else { echo "<ol>"; foreach($_POST as $field => $value) { echo "<h3><li> $field = $value</li></h3>"; } echo "</ol>"; } } else { include("exercise_4_form.inc"); } ?> Edited November 15, 2014 by mac_gyver code tags around posted code please Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/ Share on other sites More sharing options...
ginerjm Posted November 14, 2014 Share Posted November 14, 2014 Way too much code to look at. Do you really think we need to see the css? How about showing us the part where you build the dropdown? At the completion of that build, save the var that you (hopefully) just built in $_SESSION. Then where you actually output all your html (cause I just KNOW that you didn't dare to do it inside that loop) include that session var. When the page comes back to your script before you start the build next time see if the session var exists. There you go Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496536 Share on other sites More sharing options...
anthonyJ Posted November 14, 2014 Author Share Posted November 14, 2014 Yes sorry heres the code to build the dropdown: if($field == "state"){echo "<label for='$field'>$label</label><select id='$field' name='$field'>\n";foreach ( $states_list as $abbr => $sname ){echo "<option value='$abbr'>$sname</option>\n";}echo "</select>\n"; Then how do I get this dropdown to keep the selection of the user on the next build? hmmm I am pretty bad at this stuff but can try a few things I guess. Use the $sname variable in the good data maybe, not sure. Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496537 Share on other sites More sharing options...
ginerjm Posted November 14, 2014 Share Posted November 14, 2014 You keep it the same way you would for any dropdown - you set the 'select' attribute on the pertinent option tag. In your case you would need to re-build the list when you get a selection from the user. As for re-using the saved SESSION var I guess you would have to trash it and re-build it when you get a new selection. And don't say you don't know how - look it up first Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496565 Share on other sites More sharing options...
mac_gyver Posted November 14, 2014 Share Posted November 14, 2014 since this is all one page, all you really need to accomplish is outputting a selected="selected" attribute (valid for all modern html/xhtml versions) inside the correct <option ...> tag when you are building the option list. you would do this by testing whatever variable holds the submitted form value for the <select > menu. if that variable exists and is equal to the current $abbr value, you would output the selected="selected" attribute. Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496582 Share on other sites More sharing options...
anthonyJ Posted November 14, 2014 Author Share Posted November 14, 2014 Way in over my head here. How exactly do I you set the 'select' attribute on the pertinent option tag I see this if($field == "state") {echo "<label for='$field'>$label</label><select id='$field' name='$field'>\n";foreach ( $states_list as $abbr => $sname ){echo "<option value='$abbr'>$sname</option>\n"; [{{I am assumming here somewhere???}}]}echo "</select>\n"; This is making my head explode, I am horrible with this stuff. Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496615 Share on other sites More sharing options...
ginerjm Posted November 15, 2014 Share Posted November 15, 2014 If you are attempting to be any kind of developer, you will need to do some reading and learning. Look up some html using google. How about trying "html option tag" to see what it should look like. We could show you but then you wouldn't learn Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496621 Share on other sites More sharing options...
anthonyJ Posted November 15, 2014 Author Share Posted November 15, 2014 Alrighty then. Thanks Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496629 Share on other sites More sharing options...
mac_gyver Posted November 15, 2014 Share Posted November 15, 2014 i went through your code and have the following lists of don't and do suggestions - don't - don't loop over all $_POST data. a hacker can feed your code 100's or 1000's of $_POST variables. you should have an internal list of expected fields (your $rows array) and loop over this list, checking the corresponding input value. don't use the @ error suppressor in code. rather than suppress errors, which makes troubleshooting harder, find a way of programming that doesn't regularly throw php errors that you would be tempted to suppress. don't use extract() in your code, especially on external data since this will let a hacker set any php variable to the value he wants, not just the variables you expect. don't use preg_match() just to test which field you are operating on. don't repeat the same code (your preg_match() format tests) when the only thing that is different between each block of code are the data values. you can expand your array holding the form field definitions to include the preg_match() pattern and what error text to use for each field. don't use variable-variables unless absolutely necessary. in your case, you already have the existing data values in an array. simply use the values from that array. don't repeat yourself - DRY. you have code and data that's being repeated on the page (the include for the form and arrays of submitted form data). you should re-factor your logic to use just one instance of any code and data. don't use $_SERVER['PHP_SELF'], without passing it through htmlentities(). in some versions of php this includes the query string that was used to request your page, allowing cross site scripting. you can use an blank action='' attribute to submit a form to the same page. do - initialize array variables before use. this will make testing those arrays easier, since you won't need to suppress php errors when the array hasn't been assigned any entries perform as many validation tests as possible each time the form is submitted. your current code requires that all required fields be non-empty before doing any of the other validation tests. for a field that has a value, you should validate it and output all the possible validation errors at once. use your internal list of form fields (expanded to include a required/optional control value) to control the required field check so that you don't need to hard-code out any optional fields. put static code/values outside of loops. your current definition of the preg_match strings are inside of a loop, wasting time each pass through the loop. the optional first name field, when it is non-empty, should be validated to insure it contains only expected characters. the include file with your form should only include code block(s) needed for the form, not the entire html markup for the page. your current code is outputting the error $message before the <html> tag, resulting in an invalid html page. your main page should be where the main html for the page is at. variable names should indicate the purpose of the variable. your $rows array, that defines the form fields, should be named something like $form_definition or similar. use htmlentities() when echoing external data back onto a web page to prevent cross site scripting and to prevent an special html characters in the values from breaking the html on the page use css to style elements, not inline styling (your error messages.) the first/default choice in your state option list should not be one of the valid choices so that you can detect when a state hasn't been selected 1 Quote Link to comment https://forums.phpfreaks.com/topic/292452-how-can-i-apply-a-usa-state-drop-down-menu-selection-to-stay-on-form-include-re-load/#findComment-1496657 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.