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.

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

报告相同问题?

悬赏问题

  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等