views:

247

answers:

5

I am having problems figuring out how to retain users data when the validation fails. I am somewhat new to PHP so I might be making some huge mistakes in my logic.

Currently if the validation fails all the fields are wiped clean and $_Post data is also gone.

Here is some code assuming the user enters an invalid email I want the Name field to be retained. This code is not working.

<?php
if($_POST['doSubmit'] == 'Submit') {

   $usr_name = $data['Name'];
   $usr_email = $data['Email'];

   if (isEmail($usr_email)==FALSE){
       $err = "Email is invalid.");
       header("Location: index.php?msg=$err");
       exit();
    }

   //do whatever with data

}

if (isset($_GET['msg'])) {
   $msg = mysql_real_escape_string($_GET['msg']);
   echo "<div class=\"msg\">$msg</div><hr />";
}
if (isset ($_POST['Name'])){
   $reusername = $_POST['Name'];}
else{$reusername = "NOTHING";}//to test

 ?>
 <form action="index.php" method="post" >
 <input name="UserName" type="text" size="30" value="<?echo $reusername;?>">
 <input name="Email" type="text" size="30">
 <input name="doSubmit" type="submit" value="submit">
 </form>




 }
+2  A: 

You can use AJAX to submit your form data to your PHP script and have it return JSON data that specifies whether the validation was successful or not. That way, your fields won't be wiped clean.

Another way is to send back the recorded parameters to the posting page, and in the posting page, populate the fields using PHP.

However, I think the first solution is better.

UPDATE

The edit makes your code clearer and so I noticed something. Your input field is called UserName in the HTML, but you are referring to Name in PHP. That's probably why it's not working. Is your field always being filled with the value NOTHING? Make sure the name of the input field and the subscript you are using in $_POST are the same.

Also, there's no need to redirect to another page (using header) if you have an error. Maintain an $errors array or variable to print error messages in the same page. But like I mentioned before, it's probably better to use the JSON approach since then you can separate your view layer (the html) from the PHP (controller layer). So you'd put your HTML in one file, and your PHP in another file.

Vivin Paliath
+1 - good catch on the html -> php discrepency in the field names.
prodigitalson
the UserName Name mix up was just me throwing something together. But you as well as most of these comments have answered my question.
brad
+1  A: 

EDIT:

Vivin had commented that my assumption regarding the header was incorrect and he was right in that. Further more it looks like what the OP is doing is essentially what i layed out below albeit in a less structured fashion. Further Vivin - caught what is likely the actual problem here - the html name and the array key $_POST do not match.


Its wiped clean because you are using header to redirect to another page. Typicaly you would have a single page that validates the data and if ok does something with it and returns a success view of some sort, or that returns an error view directly showing the form again. By using header youre actually redirecting the browser to another page (ie. starting up an entirely new request).

For example:

// myform.php

  if(strtolower($_SERVER['REQUEST_METHOD']) == 'get')
  {
      ob_start();
      include('form.inc.php'); // we load the actual view - the html/php file
      $content = ob_get_clean();
      print $content;  // we print the contents of the view to the browser
      exit;
  }
  elseif(strtolower($_SERVER['REQUEST_METHOD']) == 'post')
  {
     $form = santize($_POST); // clean up the input... htmlentities, date format filters, etc..
     if($data = is_valid($form))
     {
       process_data($data); // this would insert it in the db, or email it, etc..
     }
     else
     {
        $errors = get_errors(); // this would get our error messages associated with each form field indexed by the same key as $form
        ob_start();
        include('form.inc.php'); // we load the actual view - the html/php file
        $content = ob_get_clean();
        print $content;  // we print the contents of the view to the browser
        exit;

     } 
   }

so this assumes that your form.inc.php always has the output of error messages coded into it - it just doesnt display them. So in this file you might see something like:

<fieldset>
  <label for="item_1">
    <?php echo isset($error['item_1']) ? $error['item_1'] : null; ?>
    Item 1: <input id="item_1" value="<?php echo $form['item_1'] ?>" />
  </label>
</fieldset> 
prodigitalson
A: 

Could do something similar to if failed then value=$_POST['value']

But vivin's answer is best. I don't know much about AJAX and wouldn't be able to manage that.

Rob
A: 

Ok, firstly header("Location: index.php?msg=$err"); is not really required. It's best practice not to redirect like this on error, but display errors on the same page. Also, redirecting like this means you lose all of the post data in the form so you can never print it back into the inputs.

What you need to do is this:

<input name="Email" type="text" size="30" value="<?php print (!$err && $usr_email ? htmlentities($usr_email, ENT_QUOTES) : '') ?>">

Here I'm checking whether any errors exist, then whether the $usr_email variable is set. If both these conditions are matched the post data is printed in the value attribute of the field.

The reason I'm using the function htmlentities() is because otherwise a user can inject malicious code into the page.

Rowan
A: 

You appear to be processing the post on the same page as your form. This is an OK way to do things and it means you're nearly there. All you have to do is redirect if your validation is successful but not if it fails. Like this

<?php
if( isset( $_POST['number'] ) ) {
    $number = $_POST['number'];
    // validate
    if( $number < 10 ) {
        // process it and then;
        header('Location: success_page.php');
    } else {
        $err = 'Your number is too big';
    }
} else {
    $number = '';
    $err = '';
}

?>


<form method="POST">
    Enter a number less than 10<br/>
    <?php echo $err ?><br/>
    <input name="number" value="<?php echo $number ?>"><br/>
    <input type="submit">
</form> 
meouw