在表单错误检查后将表单数据保留在输入字段内

时间:2014-05-16 19:58:28

标签: php html forms

我有一个小表单,我正在使用php进行一些简单的错误检查,所有看起来都很好,但我注意到当用户提交表单时,在错误检查发生后,所有数据都从字段中删除。

这就是我所拥有的

<?php if($show=="true"):?>
<input name="fname" type="text" value="<?php if(isset($_POST['name']){echo $_POST['name';]})?>"><?php echo $errorname; ?>

<input name="email" type="text" value="<?php if(isset($_POST['name']){echo $_POST['name';]})?>"><?php echo $erroremail; ?>
<input type="submit" value="submit">
<?php else: ?>
<h2>Your Message was sent</h2>

 <?php endif;?>
<?php
    if(empty($_POST['name'])){
         $show="true";
         $errorname="please enter your name";
     }
     elseif(empty($_POST['email'])){
        $show=true;
        $erroremail="please end your email";
     }else
        $show=false;
        //Send data as email;

    ?>

1 个答案:

答案 0 :(得分:0)

如果您只想检查字段是否为空(这很奇怪),您可以使用上次提交的帖子值。之后,只需使用empty(),如果确实存在错误,将它们放入数组(收集它们)并在提交后打印它们。考虑这个例子:

<?php
$errors = array();

if(isset($_POST['submit'])) {
    $fname = trim($_POST['fname']);
    $email = trim($_POST['email']);

    if(empty($fname)) {
        $errors['fname'] = 'please enter your name';
    }
    if(empty($email)) {
        $errors['email'] = 'please enter your email';
    }
}
?>

<form method="POST" action="index.php">
    Name: <input type="text" name="fname" value="<?php echo isset($_POST['fname']) ? $_POST['fname'] : ''; ?>" /> <span style="color: red;"><?php echo isset($errors['fname']) ? $errors['fname'] : ''; ?></span><br/>
    Email: <input type="text" name="email" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>" /> <span style="color: red;"><?php echo isset($errors['email']) ? $errors['email'] : ''; ?></span><br/>
    <input type="submit" name="submit" value="Submit" />
</form>

<?php if(isset($_POST['submit']) && empty($errors)): ?>
    <h2>Your Message was sent.</h2>
<?php endif; ?>