Conditional SQL statement
Posted: Sun Jan 18, 2004 5:03 pm
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.
I would be grateful for any input provided.
I would be grateful for any input provided.
Code: Select all
<?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;
?>