Validating Select Box with PHP?

15,898

Solution 1

A simpler method would be to compare the variable against a list of allowed values:

if (!in_array($gender, array("", "Male", "Female"))) {
    $error[] =

Note how the array list also includes the empty "" string.

Solution 2

The problem is not the select value but your conditional. I think you want this instead:

if(!empty($gender) && $gender != "Male" && $gender != "Female"){
    $error[] = "Gender not valid";
}

Note that all the conditionals are AND'd together.

Share:
15,898
PHPLOVER
Author by

PHPLOVER

Updated on June 07, 2022

Comments

  • PHPLOVER
    PHPLOVER almost 2 years

    I have coded in PHP but today for the first time I needed to validate a select box and am shocked to realise I am not actually sure how to. Basically this is my HTML: (ignore the session stuff in the code)

    <label for="gender">Gender</label>
    <select id="gender" name="gender" class="select option">
    <option<?php if( $_SESSION['gender'] === "" ) { echo ' selected="selected"'; } ?>  value="">&nbsp;</option>
    <option<?php if( $_SESSION['gender'] === "Male" ) { echo ' selected="selected"'; } ?> value="Male">Male</option>
    <option<?php if( $_SESSION['gender'] === "Female" ) { echo ' selected="selected"'; } ?> value="Female">Female</option>
    </select>
    

    Basically I wrote the php code below thinking it would validate it but whether I tamper with the values or not in browser using Firebug it always returns gender not valid error.

    The rest of my edit profile form works fine so does the select box (without validation) but obviously I need to validate it as the male, female or nothing is updated in database on user profile. I do mysql_real_escape string etc but not added that here just out of simplicity etc.

    $gender = $_POST['gender'];
    
    if(!empty($gender) && $gender != "Male" || $gender != "Female"){
        $error[] = "Gender not valid";
    }
    

    If someone could please explain how I check the values from select box to ensure they not been tampered with and contain male, female or no value that would be much appreciated. Maybe I am doing it the wrong way.

  • PHPLOVER
    PHPLOVER about 13 years
    Thanks Mario seems like the more logical best solution so thank you :)