表单字段,输入数据在发生错误时保留

表单字段,输入数据在发生错误时保留

问题描述:

How to make already typed data not disappeared when error occurs in PHP form.

Example : if I type name and address correctly but I made mistake with email and error occurs I want correct fields stay the same, how I do that?

 <div class="elements">
  <label for="name">Name :</label>
  <input type="text" id="name" name="name" size="50" value="<?php echo $name; ?>" />
</div>
<div class="elements">
  <label for="e-mail">E-mail :</label>
<input type="text" id="e-mail" name="e-mail" size="50"  value="<?php echo $email; ?>"/>
</div>
<div class="elements">
  <label for="Password">Password:</label>
  <input type="password" id="Password" name="Password" size="50" />
</div><input type="text" id="name" name="name" size="50"  " />

I tried echo that but when page is loaded for first time something like that is visible in form field
Notice: Undefined variable: name in C:\xampp\htdocs\MyOnlineStore\members\index.php on line 173

This is called sticky forms.

You are getting the error string because your variable is empty, that's right. You could simply silence them by adding an at-sign in front of your variable, but that isn't the best practice. What you need to do is check if the value exists, and display if so, or display something else if not.

I made a helper function that can check to see wether to display what has come in from $_POST or a default value. put in the input

event name<br />
<input type="text" 
       style="width:100%" 
       name="title" 
       value="<?=stickyRow($_POST,'title','')?>" />


function stickyRow($array,$index,$default = ''){

    if(empty($array[$index]) || $array[$index] == ''){
        return $default;
    }else{
        return $array[$index];
    }

}

The $array is usually the returned $_POST, $_GET or $_RESULT array. The $index is the key that belongs in that input. If that is key populated, it shows it in the form, if not, it shows a default value.

Hope this helps.

I think for the correct input field you can save them in sessions.