Greetings,

I am new to PHP and I am trying to write a form validation script for my company. The form to be validated is an application for employment, many different fields of all types.

When submitted, the form is validated by an external PHP script. The script returns errors on the screen and prints out the information submitted by the user underneath. This part is no problem, everything works fine.

The major headache comes into play when the user must return to the form and enter any information left out when they first submitted (ie., missing fields reported by the validation script). I have been successful in maintaining the information entered into text boxes and text areas using the #value="$_POST['field_name']"#, but the radio buttons, check boxes, and drop-down menus reset every time the form is displayed. So, the user then needs to recheck every field or else they will encounter an error (fields not checked/selected).

I have posted under the Newbie board and have been searching Google and other forums for over a week now. I MUST complete the project, unfortunately my client does not understand what is involved with such a large validation script.

So, in short: Validation script works fine. What I am trying to accomplish: Maintaining checked boxes and selected radio buttons when the user hits the Back button or clicks a link to return to the form.

Seems like a simple enough problem, but I cannot find a solution to save my life. PLEASE HELP πŸ™

Thanks....
Ben

    Here's a quick example:

    <?php
    
    $myvar = (isset($_POST['myvar']) ? addslashes($_POST['myvar']) : '');
    
    ?>
    <select name="myvar">
    <option value="one" <?php echo ($myvar == '1' ? 'checked' : ''); ?>>One</option>
    <option value="two" <?php echo ($myvar == '2' ? 'checked' : ''); ?>>Two</option>
    <!-- etc. - same concept for radio buttons -->
    </select>

      OK -- that looks like it may work, but could you explain how to implement it? Should the PHP code go on the page with the form, or on the validation page -- or both? And where should the code be placed?

      I have tried several different things, still resetting the field.

      I feel I'm one step closer, more info please! Thanks πŸ™‚

      -Ben

        Well, that code should go whever you want to re-display a dropdown (or radio button) that the user has already submitted a value for and you wish to auto "select" the value they last used.

        As to how to implement it... I don't know how much more I can explain it as I've already given you the code. Basically you just copy and paste the 'checked' bit from my code into yours and modify the variable name.

          bradgrafelman wrote:

          Well, that code should go whever you want to re-display a dropdown (or radio button) that the user has already submitted a value for and you wish to auto "select" the value they last used.

          As to how to implement it... I don't know how much more I can explain it as I've already given you the code. Basically you just copy and paste the 'checked' bit from my code into yours and modify the variable name.

          OK, I made a very simple version of the form I will be using. Try it by leaving one or both of the text areas blank. The data entered into the text field is kept in place when the form refreshes, however the selection menu is not. The form is located here, here is the PHP code:

          <?php
          $form_block = "
          <form method=\"post\" action=\"$PHP_SELF\">
          <p><strong>Name: </strong> <input type=\"text\" name=\"name\" size=\"40\" value=\"$_POST[name]\"></p>
          <p><strong>E-mail: </strong> <input type=\"text\" name=\"email\" size=\"30\" value=\"$_POST[email]\"></p>
          <select name=\"test\">
          <option value=\"one\">One</option>
          <option value=\"two\">Two</option>
          </select>
          <input type=\"hidden\" name=\"op\" value=\"ds\">
          <input type=\"submit\" name=\"submit\" value=\"submit\">
          </form>";
          if ($_POST[op] != "ds") {
          echo "$form_block";
          } else if ($_POST[op] == "ds") {
          if (empty ($_POST['name'])) {
          	$name_err = "<font color=red>Please enter a name.</font><br />";
          	$send = "no";
          }
          if (empty ($_POST['email'])) {
          	$email_err = "<font color=red>Please enter your e-mail.</font>";
          	$send = "no";
          }
          if ($send != "no") {
          echo "Name: $name<br>
          Email: $email";
          }
          if ($send == "no") {
          	echo $name_err;
          	echo $email_err;
          	echo $form_block;
          }
          }
          ?>
          

          Now, how exactly do I use the code you posted to keep my radio buttons (or check boxes, or menus) from resetting this way? I have tried putting that bit of HTML in a variety of places with no luck.

          Also, I am not trying to redisplay singular fields in another page, I am trying to maintain data entered into a whole form, then display error messages above (as in the example).

          Thanks πŸ™‚
          Ben

            I'm having the exact same problem, did you ever get a resolution?

              Try this basic form,

              <?php
              if($_POST['submit']=="send") {
                 $errcount = 0;
                 $error1="<font face='Verdana' size='2'><span style='color:red'>";
                 $error2="<font face='Verdana' size='2'><span style='color:red'>";
                 $error3="<font face='Verdana' size='2'><span style='color:red'>";
              
              
                if(preg_match('/^[a-zæøΓ₯Γ†Γ˜Γ…0-9_-]{4,}$/i', $_POST['username'])){
                  $user = $_POST['username'];     
              }
                  else {
                  $error1 .= "<font face='Verdana' size='1'>Required! min 4";
                  $errcount++;  
                   }   
              
                 //check correct email  
              if(preg_match('/^[\w]+[-\w._]*@[\w]+[-\w]+(\.[\w]+[-\w]+)*\.[\w]{2,6}$/ ', $_POST['email'])){ $email = $_POST['email']; } else { $error2 .= "<font face='Verdana' size='1'>Required!"; $errcount++;
              } //check terms and conditions check box if(!isset($_POST['agree'][0])) { $error3.="<font face='Verdana' size='1'>Required!<br />"; $errcount++; } if ($errcount !=0) { //displays errors in form boxes } else { include("dbinfo.inc.php"); $conn = mysql_connect($host, $username, $password) or die(mysql_error()); mysql_select_db($database,$conn) or die(mysql_error()); //$connect = mysql_connect("localhost",'user','pass') or die ("SQL unavailable."); //$db = mysql_select_db('dbname',$connect) or die ("Unable to select database"); //$user = $_POST['username']; //$passw=$_POST['password']; $query="SELECT * FROM sometable WHERE username='$user'"; $result = mysql_query($query) or die ("Could not run query."); $num=mysql_num_rows($result); if ($num ==0) { function generate_password() { $salt = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"; srand((double)microtime()*1000000); $pass = ""; for($count = 0; $count < 8; $count++) { $num = rand() % 33; $tmp = substr($salt, $num, 1); $pass = $pass.$tmp; } return $pass; } $randpass = generate_password(); $passw = $randpass; include("dbinfo.inc.php"); $user = $_POST['username']; $email = $_POST['email']; mysql_connect($host,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query = "INSERT INTO sometable VALUES ('','$user','$email')"; //new logon welcome page echo '<meta http-equiv="refresh" content="0;url=newlogon.php">'; } else { //$num_rows = mysql_num_rows($result); $ataken= "<font face='Verdana' size='1' color='#FF0000'>That Username is already taken, please try again "; } } } ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" > <table border="0" cellpadding="7" cellspacing="1" bordercolor="#111111" width="800" height="49" align="center"> <tr> <td width="1" height="25"><font face="Verdana" size="2" color="#000000">Username:<font face="Verdana" size="2" color="#FF0000">*</font><font face="Verdana" size="2" color="#000000"> </td> <td width="403" height="25" align="left"> <input type="text" value="<? echo $user; ?>" id="username" name="username"> <font face="Veranda" size="2"><? echo $error1; ?></font></td>
              <tr> <td width="1" height="26"><font face="Verdana" size="2" color="#000000">Email:<font face="Verdana" size="2" color="#FF0000">*</font><font face="Verdana" size="2" color="#000000"></font></td> <td width="403" height="26"><font face="Verdana" size="2" color="#000000"><input type="text" name="email" size="20" value="<? echo $email; ?>"></font>&nbsp;<font face="Veranda" size="2"><? echo $error2;?></font></td></tr> <tr> <td width="107" height="25"><font face="Verdana" size="2">Agree:<font face="Verdana" size="2" color="#FF0000">*</font><font face="Verdana" size="2" color="#000000"></font></td> <td width="631" colspan="3" height="35"> <font face="Verdana" size="2" color="#000000"><input name="agree" type="checkbox" id="agree" value="y" <?php if (!empty($_POST['agree'])) echo 'checked="checked"'; ?>> <font face="Verdana" size="2">&nbsp;Tick to confirm you agree to <a href="Terms and Conditions.htm" title="Conditions">Terms and Conditions</a> of Membership&nbsp;<? echo $error3; ?></font></font></td> <tr> <td width="117" height="1"><font face="Verdana" size="2" color="#000000"><input name="submit" type="submit" value="send" /><input type='button' value='Retry' onClick='history.go(-1)'> </font></td> <td width="232" height="1"><? echo $ataken; ?></td> </tr> </table> </form> ?>

              hope this helps

              roscor

                zoidy wrote:

                I'm having the exact same problem, did you ever get a resolution?

                Yes, I FINALLY figured out a solution on my own. I used sessions to keep data from all fields on the form (one page contains the form, another page validates it) and then posted the results from the $_SESSION field to the value attribute of each field.

                As for the check boxes, I made an if and else if statement to set the status to checked. Example:

                if ($_SESSION[check1] == 'Yes') {
                    $check1_y = "checked";
                } else if $_SESSION[check1] == 'No') {
                   $check1_n = "checked";
                }
                

                Then, for the radio button, I simply added an echo command to print checked, if that is what the $_SESSION reported.Same concept for drop-down menus, only I used "selected" instead of "checked."

                I am sure there is a much more complicated way to go about this, but all I need now is something that will work so I can finish the darn thing.

                Hope this helps πŸ™‚

                -Ben

                  nightmicu wrote:

                  Yes, I FINALLY figured out a solution on my own. I used sessions to keep data from all fields on the form (one page contains the form, another page validates it) and then posted the results from the $_SESSION field to the value attribute of each field.

                  As for the check boxes, I made an if and else if statement to set the status to checked. Example:

                  if ($_SESSION[check1] == 'Yes') {
                      $check1_y = "checked";
                  } else if $_SESSION[check1] == 'No') {
                     $check1_n = "checked";
                  }
                  

                  Then, for the radio button, I simply added an echo command to print checked, if that is what the $_SESSION reported.Same concept for drop-down menus, only I used "selected" instead of "checked."

                  I am sure there is a much more complicated way to go about this, but all I need now is something that will work so I can finish the darn thing.

                  Hope this helps πŸ™‚

                  -Ben

                  I'm only a relative beginner at php but couldn't using a session cookie pose a hacking risk??

                  I used this to code for a drop down in a classified ad page. It not only builds the drop down but chooses the correct choice if the user is returned upon a validation error.

                                    [CODE] 

                  <?php
                  echo '<select name="ad_type">';

                  echo '<option value="">Select one</option>';
                  echo '<option value="For Sale"';
                  if($POST['ad_type'] == "For Sale")
                  echo ' selected';
                  echo '>For Sale</option>';
                  echo '<option value="Wanted"';
                  if($
                  POST['ad_type'] == "Wanted")
                  echo ' selected';
                  echo '>Wanted</option>';
                  echo '<option value="Job Listing"';
                  if($_POST['ad_type'] == "Job Listing")
                  echo ' selected';
                  echo '>Job Listing</option>';
                  echo '</select>';
                  ?>
                  [/CODE]

                  This code goes where you want your dropdown to show.

                    From what I have read in my PHP manuals, cookies have a bad rap but are not really a security threat. And the session is per user and expires when the browser closes, so I do not see how it could pose a problem.

                    Expert input? Anyway, it is working perfectly for the job. After all was said and done, 700 lines in my validation script, 80 fields to validate on the form. And to think my client wanted it done in two days... ugh.

                    -Ben

                      Write a Reply...