表单字段不保留输入数据

时间:2013-01-21 02:45:08

标签: php forms input field isset

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

<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错误时,它没有传回任何东西?

2 个答案:

答案 0 :(得分:0)

如果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']); ?>">

答案 1 :(得分:0)

我最后不得不使用会话,因为我发布了一个流程页面,这似乎是原因,而不是SELF。花费更多时间,但做我需要的。

相关问题