0

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.

pedroyanky
  • 323
  • 2
  • 10
  • When the PHP processor run - it goes over your code line-by-line. You print the variable **before** you assign some value to it... – Dekel Dec 24 '16 at 17:44

1 Answers1

1

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; ?>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252