相同页面处理 [英] Same page processing

查看:91
本文介绍了相同页面处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与使用单独的处理页面相比,如何在同一页面上处理表单.现在,用于注册,评论提交等,我使用第二个页面来验证数据,然后提交并路由回home.php.我如何做到这一点,以便在提交时,页面本身进行验证,而不是使用第二个页面.

How can process a form on the same page vs using a separate process page. Right now for signups, comment submissions, etc I use a second page that verifies data and then submits and routes back to home.php. How can I make it so that on submit, the page itself verifies rather than using a second page.

推荐答案

您可以告诉表单提交到PHP自身,然后检查$_POST变量以进行表单处理.此方法非常适合进行错误检查,因为您可以设置一个错误,然后重新加载用户先前提交的所有信息(即不会丢失提交信息)的表单.

You can tell the form to submit to the PHP's self, then check the $_POST variables for form processing. This method is very good for error checking as you can set an error and then have the form reload with any information the user's previously submitted still in tact (i.e. they don't lose their submission).

单击提交"按钮时,它将信息发布到同一页面,并在顶部运行PHP代码.如果发生错误(根据您的检查),该表单将为用户重新加载,其中显示了所显示的错误以及用户仍在字段中提供的任何信息.如果没有发生错误,则将显示确认页面,而不是表格.

When the "submit" button is clicked, it will POST the information to the same page, running the PHP code at the top. If an error occurs (based on your checks), the form will reload for the user with the errors displayed and any information the user supplied still in the fields. If an error doesn't occur, you will display a confirmation page instead of the form.

<?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>

这篇关于相同页面处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆