PHP表单验证,刷新后保留字段值

时间:2015-08-04 10:09:18

标签: php html validation

我目前正在为网站制作注册/验证脚本,并偶然发现了一个问题。

我正在使用所有PHP来验证和使用if语句来回显错误数组。

我的问题是:刷新后如何在表单中保留用户的输入值?我必须学习AJAX吗?

  • 注意:我所关注的文件是register.php,它将数据发送到同一页面(action = "")。 form_handle.phpregister.php
  • 顶部/开头的实际验证脚本

form_handle.php CODE:

    $errors = array();

if( empty($safe_fname) || 
    empty($safe_lname) || 
    empty($safe_email) || 
    empty($safe_email_again) || 
    empty($safe_password) )
        { 
        $errors = '<p>One or more fields left empty'; 
        }
elseif( strlen($safe_password) < 6)
    { 
    $errors = '<p>Password must be atleast 6 charcters long.</p>'; 
    }

elseif($safe_email != $safe_email_again)
    { 
    $errors = '<p>E-mails do not match.</p>'; 
    } 

The form代码:

       <h2>Sign up Today!</h2>
          <form method="post" action="">
                   <span class="p" id="p1"></span><br/> 
          <input name="first_name" id="first" class="register_form cap" type="text" placeholder="First Name" />
              <br/><span class="p" id="p2"></span><br/> 
      <input name="last_name" id="second" class="register_form cap" type="text" placeholder="Last Name" />
          <br/><span class="p" id="p3"></span><br/> 
      <input name="email" id="third" class="register_form" type="text" placeholder="E-mail" />
          <br/><span class="p" id="p4"></span><br/> 
      <input name="email_again" id="fourth" class="register_form" type="text" placeholder="Re-enter E-mail" />
          <br/><span class="p" id="p5"></span><br/> 
      <input name="password" type="password" class="register_form" placeholder="Password" />
          <br/><span class="p" id="p1"></span><br/>   
      <input name="submit" id="fifth" class="register_form" type="submit" value="Create!" />

      </form>
</div>

3 个答案:

答案 0 :(得分:3)

您的代码应该像

Aug  4 15:50:25

答案 1 :(得分:2)

快速执行此操作并避免大量代码和错误是这样的:

<input type='text' name='first_name' value='<?php echo isset($_POST['first_name']) ? $_POST['first_name'] : ''; ?>' />

答案 2 :(得分:0)

您可以尝试如下 -

<input name="first_name" id="first" class="register_form cap" type="text"
    <?php
    if(isset($_POST['first_name'])) {
        echo "value='".$_POST['first_name']."'";
    } else {
        echo "placeholder='First Name'";
    }
    ?>

    />