繁体   English   中英

表单字段不保留输入数据

[英]Form field not retaining input data

我似乎无法弄清楚为什么提交表单时,表单会返回错误消息,提示它不保留我在字段中输入的内容。 这是我的输入字段的示例:

<input type="text" value="<?php if (isset($_POST['the_field'])) echo $_POST['the_field'];?>" name="the_field" id="the_field"/>

我正在使用会话进行错误消息处理。 但是我认为那不会有所作为,对吧? 有任何想法吗?

我的表格的一部分:

<form action="process.php" method="post" name="edit" id="edit">
<input type="text" value="<?php if (isset($_POST['name']))  echo htmlentities($_POST['name']);  ?>" name="name" id="name" class="text" tabindex="1"/>
<input type="text" value="<?php if (isset($_POST['the_field'])) echo $_POST['the_field'];?>" name="the_field" id="the_field"/>
<input type="hidden" value="Create" name="action"/>
<input type="submit" class="btn" value="Create New Project" />
</form>

我的PROCESS.PHP的一部分:

if(isset($_POST)){
    switch($_POST['action']){   
        case 'Create':
        $client = $_POST['client'];
            if(empty($_POST['name'])){
              $_SESSION['error'] = 'You need to enter a project name!';
              header('location: add.php');
              exit; 
            }
    }
break;
}

您是否认为这是因为NAME字段是在THE_FIELD之前处理的,并且当NAME错误时,它没有传回任何东西吗?

如果isset没关系,要显示post发送的内容,您必须这样写$_POST['the_field']

<input type="text" value="<?php echo htmlspecialchars($_POST['the_field']);?>" name="the_field" id="the_field"/>

更新

不要sessions用于此类事情。

if (isset(whatever))
// this 
else
// other

无论如何,您都用post值重新填充输入:

<input type="text" value="<?php echo htmlspecialchars($_POST['the_field']);?>"

我的意思是,您必须在输出html之前处理所有post 例如:

if (isset(whatever))
// echo "you posted whatever, great!"
else
// post "value missing, please try again"
<input type="text" value="<?php echo htmlspecialchars($_POST['the_field']);?>"

sessions适合存储永久性数据(当然,在会话中是永久性的)要警告users输入无效,您必须在post操作后立即通知他们。 无需在sessions数据中保存信息。

总之,执行此操作的正常方法是:

<?php
if (input data is valid)
    echo 'valid'
else
    echo 'invalid'
?>
<input value="<?php echo htmlspecialchars($_POST['the_field']); ?>">

自从发布到流程页面以来,我最终不得不使用会话,这似乎是原因,而不是SELF。 需要更多时间,但可以满足我的需求。

暂无
暂无

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

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