如何在同一页面上处理表单与使用单独的处理页面。现在,对于注册、评论提交等,我使用第二个页面来验证数据,然后提交并路由回 home.php。我怎样才能做到在提交时页面本身进行验证而不是使用第二页。
最佳答案
您可以告诉表单提交给 PHP 自身,然后检查表单处理的 $_POST
变量。这种方法非常适合错误检查,因为您可以设置一个错误,然后让表单重新加载用户之前提交的任何信息仍然完好无损(即他们不会丢失他们提交的内容)。
当点击“提交”按钮时,它会将信息发布到同一页面,在顶部运行 PHP 代码。如果发生错误(基于您的检查),表单将为用户重新加载,并显示错误,并且用户提供的任何信息仍在字段中。如果没有发生错误,您将显示一个确认页面而不是表单。
<?php
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['yourname']) {
$error['yourname'] = "<p>Please supply your name.</p>\n";
}
if(!$_POST['address']) {
$error['address'] = "<p>Please supply your address.</p>\n";
}
//No errors, process
if(!is_array($error)) {
//Process your form
//Display confirmation page
echo "<p>Thank you for your submission.</p>\n";
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
}
}
?>
<form method="post" action="<?=$_SERVER['PHP_SELF']?>">
<?=$error['yourname']?>
<p><label for="yourname">Your Name:</label><input type="text" id="yourname" name="yourname" value="<?=($_POST['yourname'] ? htmlentities($_POST['yourname']) : '')?>" /></p>
<?=$error['address']?>
<p><label for="address">Your Address:</label><input type="text" id="address" name="address" value="<?=($_POST['address'] ? htmlentities($_POST['address']) : '')?>" /></p>
<p><input type="submit" name="submit" value="Submit" /></p>
</form>
关于php - 同一页面处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4783381/