粘性表单会记住输入到其中的值,当用户输入错误而没能准确完成表单,从而需要重新提交时,可能就需要使用粘性表单了。表单第一次运行时什么都不打印,因为变量没有值,如果表单在提交后再次出现,则用户之前的输入会自动显示出来。
<?php
print "<p><h3>welcome to register</h3></p>";
//添加css样式,错误信息显示红色
print '<style type="text/css" media="screen">.error{color:red;}</style>';
//检查表单是否提交
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$problem = false;//指示是否有错误
//检查每一个值
if (empty($_POST['firstname']))
{
$problem = true;
print '<p class = "erroe">please enter your first name</p>';
}
if (empty($_POST['lastname']))
{
$problem = true;
print '<p class = "erroe">please enter your last name</p>';
}
if(empty($_POST['email']))
{
$problem = true;
print '<p class = "erroe">please enter your emial</p>';
}
if (empty($_POST['password1']))
{
$problem = true;
print '<p class = "erroe">please enter password</p>';
}
if (empty($_POST['password2']))
{
$problem = true;
print '<p class = "erroe">please confirm password</p>';
}
if ($_POST['password1'] != $_POST['password2'])
{
$problem = true;
print '<p class = "erroe">confirm did not match password</p>';
}
//判断是否有错误发生
if (!$problem)
{
print"<p>you are now registered</p>";
}else
{
print "<p>please try again</p>";
}
}
?>
<!-- 创建有粘性的表单,如果用户正确的填写完了表单,则POST会重置,条件语句为false。-->
<form action="login.php" method="post">
<p>First Name: <input type="text" name="firstname" size="20" value="<?php if (isset($_POST['firstname'])) { print htmlspecialchars($_POST['firstname']); } ?>" /></p>
<p>Last Name: <input type="text" name="lastname" size="20" value="<?php if (isset($_POST['lastname'])) { print htmlspecialchars($_POST['lastname']); } ?>" /></p>
<p>Email Address: <input type="text" name="email" size="20" value="<?php if (isset($_POST['email'])) { print htmlspecialchars($_POST['email']); } ?>" /></p>
<p>Password: <input type="password" name="password1" size="20" value="<?php if (isset($_POST['password1'])) { print htmlspecialchars($_POST['password1']); } ?>" /></p>
<p>Confirm Password: <input type="password" name="password2" size="20" value="<?php if (isset($_POST['password2'])) { print htmlspecialchars($_POST['password2']); } ?>" /></p>
<p><input type="submit" name="submit" value="Register!" /></p>
</form>