简体   繁体   English

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

[英]Display form validation error message on same page using only PHP?

I'm very new to PHP and I've cobbled this together from some other answers on here. 我是PHP的新手,我从这里的其他一些答案中总结了这一点。 Can anyone show me how to get the $errMsg to display? 谁能告诉我如何显示$ errMsg? 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 } ?>

You shouldn't put the rendering of the form in the else of your if structure. 您不应该将表单的呈现形式放在if结构的else中。 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. 删除文件末尾的else { ?><?php } ?> ,它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM