1

我衷心问候我需要在单击提交按钮后保留文本框中的值,如果发现错误。基本上我想要的东西,如果用户将任何字段留空并按下保存按钮,则会弹出错误消息并且不刷新页面,它会将用户带回表单,他只需填写留空的字段...下面是我的代码

<html>
<form method="post" action="">
Enter Name  :   <input type="text" name="name" /><br/>
Enter Password  :   <input type="password" name="pass" /><br/>
<input type="submit" name="save" value="Save" />
</form>
</html>
php code
<?php
if (isset($_POST["save"]))
{
$name = $_POST["name"];
$pass = $_POST["pass"];
if (($name == '') && ($pass == '')) 
{
echo "Fields Must Be Filled...";
exit();
}
if ($name == '') {
echo "Enter Name...";
exit();
}
if ($pass == '') {
echo "Enter Password...";
exit();
}
else
{        
echo "Your name " . $name;
echo "<br/>";
echo "Your Password " . $pass;
}
}
?>
4

3 回答 3

3

只需将输入字段的值设置为与 $_POST 参数匹配即可。你的表格是..

<html>
<form method="post" action="">
Enter Name  :   <input type="text" name="name" value="<?php echo $_POST['name']; ?>" /><br/>
Enter Password  :   <input type="password" name="pass" value="<?php echo $_POST['pass']; ?>" /><br/>
<input type="submit" name="save" value="Save" />
</form>
</html>
于 2012-12-19T12:47:33.607 回答
1

输入名字 : <input type="text" name="name" /><br/>

会是这样的

<?php 

$postvalue_name = (isset($_POST['name'])) ? $_POST['name'] : 'Fill in your name..'; 
?>

Enter Name  : <input type="text" name="name" value="<?php echo $postvalue_name; ?>" /><br/>
于 2012-12-19T12:47:06.507 回答
1

首先,为您的 POST 处理提供一种更简单的方法。你可以做一个

foreach( $_POST as $key => $value )
{
   ${$key} = $value;
   //If you need to database process the data, you can put mysql_escape_string( $value );
}

现在,您的所有 POST 都将在具有字段名称的变量中。

在处理它们以查找错误等之后,您希望它们在您的表单元素的值中。你可以只使用变量

<input type="text" name="email" value="<?=$email?>">

或者,如果您使用 POST

<input type="text" name="email" value="<?=$_POST['email']?>">

此致。乔纳斯

工作代码:-)

<?php
if (isset($_POST["save"]))
{
    //Run through all objects set in the POST array
    foreach( $_POST as $key => $value )
    {
        //Set a variable named the same as the input elements name, and with the value
        ${$key} = $value;
    }
}

    $error = false;
    if( empty($name) && empty($pass) ) 
    { 
        $error = true;
        $message = "Fields must be filled...";
    }
    elseif( empty($name) )
    { 
        $error = true;
        $message = "Enter name...";
    }
    elseif( empty($pass) )
    {
        $error = true;
        $message = "Enter Password...";
    }

    if( $error == true && isset($message) )
    {
        echo $message."<br><br>";
    }
    else
    {
        echo "Your name " . $name;
        echo "<br/>";
        echo "Your Password " . $pass;
    }
?>
<html><br><br>
<form method="post" action="">
Enter Name  :   <input type="text" name="name" value="<?=(isset($name) ? $name : "")?>"/><br/>
Enter Password  :   <input type="password" name="pass" value="<?=(isset($pass) ? $pass : "")?>" /><br/>
<input type="submit" name="save" value="Save" />
</form>
</html>
于 2012-12-19T12:51:24.217 回答