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

图片转代码服务由CSDN问答提供 功能建议

我是PHP新手,我在这里拼凑了其他一些答案。 谁能告诉我如何显示$ errMsg? 目前,空白或不正确的名称会导致空白页面。 这是因为表格没有再次显示吗? 如果是这样,我该如何使用错误消息“重新加载”表单?

 &lt;?php 
 $ name =“Fred”; 
 
if(  $ _SERVER [“REQUEST_METHOD”] ==“POST”){
 
 if(!empty($ _ POST [“name”])){
 
 if($ _POST [“name”] == $ name  ){
 include(“welcomeFred.php”); 
} 
 
 else {
 $ errMsg =“名称不正确”; 
} 
 
} 
 
其他{
 $ errMsg  =“需要姓名”; 
} 
 
} 
else {?&gt; 
 
&lt; html&gt; 
 ... 
&lt; form method =“post”action =“&lt;?php  echo htmlspecialchars($ _ SERVER [“PHP_SELF”]);?&gt;“&gt; 
&lt; input type =”text“name =”name“required&gt; 
&lt; span&gt;&lt;?php echo $ errMsg;?  &gt;&lt; / span&gt; 
&lt; input type =“submit”value =“提交”&gt; 
&lt; / form&gt; 
 ... 
&lt; / html&gt; 
 
&lt;?php  }?&gt; 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题