如果发生错误,如何保持在同一页面?

时间:2013-02-17 03:13:49

标签: php

以下代码简化以说明我的问题。这是一个捕获数据的页面,它将发布捕获的信息并传递到另一个php页面进行处理。我正在尝试确保输入必填字段,但无论是否有错误,它总是会转到调用页面。 有人可以帮忙吗?

<?php
  if (empty($_POST) === false) {
    $required_field = array('first_name','last_name');
    foreach ($_POST as $key=>$value) {
    if (empty($value) && in_array($key, $required_field) === true) {
      $errors[] = 'Fields marked with asterisk are required';
      break 1;
      }
    }
  }
?>
<h1>Input Form</h1>

<?php
  if (empty($errors) === false) {
    echo output_errors($errors);
  }
?>

<form method="POST" action="UpdateDB.php" name="UpdateForm">
   <input type=text size="19" maxlength="19" name="firstname">
   <input type=text size="19" maxlength="19" name="lastname">   
   <input type="submit" value="Submit" >
</form>

3 个答案:

答案 0 :(得分:0)

通过留下空action属性(并在此处进行处理)将表单提交到当前页面,或者使用当前页面网址添加隐藏字段:

<input type="hidden" name="sourceUrl" value="<?= $_SERVER['REQUEST_URI']; ?>" />

如果有错误,请在UpdateDB.php脚本中重定向回此网址。类似的东西:

$url = $_POST['sourceUrl']; // <- sanitize this (make sure it's your site)!

header('Status-Code: 301');
header('Location: http:// ' . $_SERVER["HTTP_HOST"] . $url); 
exit; // important: stop current script

答案 1 :(得分:0)

下面的代码将检查是否使用POST方法调用页面,如果不是,它将打印输入表单。

php脚本必须存储在UpdateDB.php中,

<?php

    if(!isset($_POST)){

    echo "<h1>Input Form</h1>";
    echo "<form method="POST" action="UpdateDB.php" name="UpdateForm"> <br/>" .
       "<input type=text size="19" maxlength="19" name="firstname"> <br/>" .
       "<input type=text size="19" maxlength="19" name="lastname">   <br/>" .
       "<input type="submit" value="Submit" >" .
    "</form>";
    }

    else{
         /*Form Action code goes here*/
          }
        }
    }


    ?>

答案 2 :(得分:0)

好的,我找到了一个很好的例子来展示如何做到这一点 http://yensdesign.com/2009/01/how-validate-forms-both-sides-using-php-jquery/