doutang7661 2016-12-24 17:43
浏览 58
已采纳

如何在表单字段附近打印出错误消息,以指示PHP中的错误输出

I have this form element in my php page, and i want to echo out the error message underneath the form element.

     <form method="post" action="<?php $_SERVER['PHP_SELF']; ?>" >
        Name: <input type="text" name="username"><br>
              <span><?php echo nameErr; ?></span>
        password: <input type="password" name="password"><br>
              <span><?php echo passErr; ?></span>
        Gender:<input type="radio" name="gender" value="male">Male
               <input type="radio"  name="gender" value="female">Female
               <span><?php echo genderErr; ?></span>
       </form>

      <?php 
         if($_SERVER['REQUEST_METHOD'] == 'POST')  {
              if(empty($_POST['username'])) {
                  $nameErr = 'name can\'t be empty';
                  else{
                      $username = $_POST['username'];
                  }
               if(empty($_POST['password'])) {
                  $passErr = 'Password can\'t be empty ';
                   else{
                        $password = $_POST['password'];
                  }
               if(empty($_POST['gender'])) {
                      $genderErr = 'Gender cant be empty';
                  }else{
                        $gender = $_POST['gender'];
                  }

       }
         }
      ?>

The major problem is that when i the page is ran, it show error messages that variable $nameErr is not defined, $passErr is not defined, and $genderErr is not defined, My question is that how can i actually notified users of error messages where necessary and it should be close to the form element too.

  • 写回答

1条回答 默认 最新

  • dongzhonggua4229 2016-12-24 17:44
    关注

    The way you have given is all wrong. You forgot two things:

    1. $ for the variables.
    2. Since we know this place correctly, we can happily suppress the errors by placing a @ in front.

    Change it this way:

    <?php echo @$nameErr; ?>
    <?php echo @$passErr; ?>
    <?php echo @$genderErr; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题