doukeng7426 2017-02-13 13:36
浏览 72
已采纳

仅使用PHP在同一页面上显示表单验证错误消息?

I'm very new to PHP and I've cobbled this together from some other answers on here. Can anyone show me how to get the $errMsg to display? At present, a blank or incorrect name leads to a blank page. Is this because the form isn't being displayed again? If so, how should I go about 'reloading' the form with the error message?

<?php
$name = "Fred";

if ($_SERVER["REQUEST_METHOD"] == "POST") {

  if (!empty($_POST["name"])) {

      if ($_POST["name"] == $name) {
        include("welcomeFred.php");
      }

      else {
        $errMsg = "Incorrect name";
      }

  }

  else {
    $errMsg = "Name required";
  }

}
else { ?>

  <html>
  ...
  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
    <input type="text" name="name" required>
    <span><?php echo $errMsg;?></span>
    <input type="submit" value="Submit">
  </form>
  ...
  </html>

<?php } ?>
  • 写回答

1条回答 默认 最新

  • dongyilai4214 2017-02-13 13:40
    关注

    You shouldn't put the rendering of the form in the else of your if structure. This is the reason your form isn't loaded when you submit the form.

    Remove the else { ?> and <?php } ?> at the end of your file and it should work fine.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?