skip to Main Content
<label>Gender<span class="note">*</span>:</label>
<select name="gender">
    <option value="1" selected <?= ($_POST['gender'] == "1")? "selected":"";?>>Select</option>
    <option value="male" <?= ($_POST['gender'] == "2")? "selected":"";?>>Male</option>
    <option value="female" <?= ($_POST['gender'] == "3")? "selected":"";?>>Female</option>
</select>
<?php echo "<p class='note'>".$msg_gender."</p>";?>
if (isset($_POST['submit'])) {
    $gender = $_POST['gender'];
    if($gender != "2" || $gender != "3"){
        $msg_gender = "Gender not valid";
    }
}

If the $msg_gender="" the form will be valid, else it’ll say gender invalid. But it says gender invalid at every stage no matter which option i select

3

Answers


  1. Your value is not 3 or 2 but ‘male’ or ‘female’ so you must change your condition to

    if($gender != "male" || $gender != "female"){
            $msg_gender = "Gender not valid";
        }
    

    Or change your option values

    <option value="2" <?= ($_POST['gender'] == "2")? "selected":"";?>>Male</option>
        <option value="3" <?= ($_POST['gender'] == "3")? "selected":"";?>>Female</option>
    
    Login or Signup to reply.
  2. change your code to this:

    if($gender != "female" || $gender != "male"){
        $msg_gender = "Gender not valid";
    }
    

    the option value is what is actually being sent

    Login or Signup to reply.
  3. <?php 
    $gender="";
    $msg_gender="";
    foreach($_POST as $k=>$v){$$k=$v;}
    if(isset($_POST['submit'])) {
        $gender = $_POST['gender'];
        if($gender == "male" or $gender == "female"){
            $msg_gender = "Selected ".$gender;
        }
        else
        {
            $msg_gender = "Gender not valid";
        }
    }
    ?>
    <form method="post" action="<?php $_SERVER['PHP_SELF']?>">
    <label>Gender<span class="note">*</span>:</label>
    <select name="gender">
        <option value="1" selected <?= ($gender == "1")? "selected":"";?>>Select</option>
        <option value="male" <?= ($gender == "male")? "selected":"";?>>Male</option>
        <option value="female" <?= ($gender == "female")? "selected":"";?>>Female</option>
    </select>
    <input type="submit" value="Submit" name="submit" />
    </form>
    <?php echo "<p class='note'>".$msg_gender."</p>";?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search