简体   繁体   English

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

[英]Keep form data inside input fields after form error checking

I have a small form, Im doing some simple error checking with php and all looks to be well but I notice when users submit the form, after the error checking happens all data is removed from the fields. 我有一个小的表格,我用php做了一些简单的错误检查,看起来一切都很好,但是我注意到当用户提交表格时,错误检查发生后,所有数据都从字段中删除了。

Here is what I have 这是我所拥有的

<?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;

    ?>

If you just want to check if fields are empty (which is weird), you could just use the post values on the last submission. 如果您只想检查字段是否为空(这很奇怪),则可以仅使用上次提交的帖子值。 After that, just use empty() , if there are indeed, errors, put them inside an array (gather them) and print them after submission. 之后,只需使用empty() ,如果确实存在错误,则将它们放入数组中(收集它们)并在提交后打印它们。 Consider this example: 考虑以下示例:

<?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; ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM