I\'m getting a string from a $_GET and I want to test if it could be a boolean, before I use it for a part of a mysql query. Is there a better way of doing it than:
For what it's worth, if you really wanted to accept "yes" or "no" as valid input from the user, then I'd do something like this:
function toBoolean($string){
$string = strtolower($string);
if ($string == "true" || $string == "1"|| $string == "yes" )
return true;
elseif ($string == "false" || $string == "0" || $string == "no")
return false;
else
throw new Exception("You did not submit a valid value, you naughty boy");
}
try {
$query = "SELECT * FROM my_table WHERE male=" . (toBoolean($_GET['male']) ? "1" : "0" );
$result = mysql_query($query) or die(mysql_error());
} catch (Exception $e) {
// handle bad user input here
}
You can use is_bool
to test your string:
if(is_bool($val)){
// is boolean
}else{
// not a boolean
}