I have a form with about 20 fields that users will need to search. I'm having trouble using the Select statement to correctly produce results. I'm not sure if I'm doing this correctly, but I'm trying to make it dynamic - using a series of IF statements to tell if the field contains a value and then using the SELECT statement to only search with those fields that contain a value. If I use AND, I don't get anything and if I use OR I get all results instead of the results that were specified in the search fields. The code I'm using is below:
$query = "SELECT * FROM source_list WHERE ";
if ($topic == "Please Select") {
$query .= "topic='' AND (";
} else {
$query .= "topic='$topic' AND (";
}
if ($first !== '') {
$query .= "first LIKE '%.$first.%' AND ";
}
if ($last !== '') {
$query .= "last LIKE '%.$last.%' AND ";
}
if ($area !== '') {
$query .= "area LIKE '%.$area.%' AND ";
}
if ($phone !== '') {
$query .= "phone LIKE '%.$phone.%' AND ";
}
if ($homeoffice !== '') {
$query .= "homeoffice LIKE '%.$homeoffice.%' AND ";
}
if ($area2 !== '') {
$query .= "area2 LIKE '%.$area2.%' AND ";
}
if ($phone2 !== '') {
$query .= "phone2 LIKE '%.$phone2.%' AND ";
}
if ($address !== '') {
$query .= "address LIKE '%.$address.%' AND ";
}
if ($city !== '') {
$query .= "city LIKE '%.$city.%' AND ";
}
if ($state !== '') {
$query .= "state LIKE '%.$state.%' AND ";
}
if ($zip !== '') {
$query .= "zip LIKE '%.$zip.%' AND ";
}
if ($business !== '') {
$query .= "business LIKE '%.$business.%' AND ";
}
if ($title !== '') {
$query .= "title LIKE '%.$title.%' AND ";
}
if ($email !== '') {
$query .= "email LIKE '%.$email.%' AND ";
}
if ($age !== '') {
$query .= "age LIKE '%.$age.%' AND ";
}
if ($race !== '') {
$query .= "race LIKE '%.$race.%' AND ";
}
if ($category !== '') {
$query .= "category LIKE '%.$category.%' AND ";
}
if ($faith !== '') {
$query .= "faith LIKE '%.$faith.%' AND ";
}
if ($comments !== '') {
$query .= "comments LIKE '%.$comments.%'";
}
$query .= " 1)";
$result = mysql_db_query($database, $query, $connection) or die ("Error in query: $query. " . mysql_error());
I'm not sure what I'm doing wrong. I am sure it's something simple. Any help would be greatly appreciated.