I've developed a search script. The goal of it was that if a person chose not to fill out a search field it, that sql statement would not include it. However, it seems i'm having that problem on a couple of the fields such as agemin and agemax reflecting nothing and location as well.
<?php
$sql = "SELECT * FROM users WHERE (id > 0)";
if(isset($_POST['uname'])){
$sql .= " AND user LIKE '%".$_POST['uname']."%'";
}
if(isset($_POST['agemin'])){
$sql .= " AND age > ".$_POST['agemin'];
} else {
$sql .= " AND age > 18";
}
if(isset($_POST['agemax'])){
$sql .= " AND age < ".$_POST['agemax'];
} else {
$sql .= " AND age < 80";
}
if(isset($_POST['location'])){
$sql .= " AND location LIKE '%".$_POST['location']."%'";
}
if(isset($_POST['sex'])){
if($_POST['sex'] == "any"){
$sql .= " AND (sex='male' OR sex='female')";
} else {
$sql .= " AND sex='".$_POST['sex']."'";
}
} else {
$sql .= " AND (sex='male' OR sex='female')";
}
$sql .= " ORDER BY create_date";
echo $sql;
?>
AFAIK, in forms, if you have an input form field of type text, it will always be set. Ie:
<input type="text" name="agemin">
$_POST["agemin"] will always be set, even if it is empty. It will just contain an empty string.
If you have checkboxes or radio buttons or select dropdowns, then isset() will be useful, otherwise you should use empty(). Or a combination of isset() and empty().