Home > Enterprise >  I'm trying to take gender as input in php but I can't validate the input
I'm trying to take gender as input in php but I can't validate the input

Time:11-11

<label>Gender<span >*</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

CodePudding user response:

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>

CodePudding user response:

change your code to this:

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

the option value is what is actually being sent

CodePudding user response:

<?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 >*</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>";?>
  • Related