Reputation: 71
Been searching all over for this but cant find an answer so thought I would ask here.
I have 5 drop down 'option box' lists whose data is populated from a database. The database information is about a user selecting a computer manufacture from the first drop down list, a computer type from the second, a computer colour from the third and finally a minimum and maximum price from the fourth and fifth drop down lists.
These user selected variables are then posted to a php 'search' page and a query is run on them. My question is, if (for example) a user only selected a computer 'manufacture' and 'make' and left all the other option boxes blank, how would I run this on my SQL search? Would I need to set then 'non set' variables as wildcards?
Any help would be appreciated!
Upvotes: 1
Views: 951
Reputation: 15616
SELECT * FROM TABLE WHERE
COLUMN_NAME_1 = IF('".$select_result_1."'='',COLUMN_NAME_1,'".$select_result_1"') AND
COLUMN_NAME_2 = IF('".$select_result_2."'='',COLUMN_NAME_2,'".$select_result_2"') AND
COLUMN_NAME_3 = IF('".$select_result_3."'='',COLUMN_NAME_3,'".$select_result_3"') AND
COLUMN_NAME_4 = IF('".$select_result_4."'='',COLUMN_NAME_4,'".$select_result_4"') AND
COLUMN_NAME_5 = IF('".$select_result_5."'='',COLUMN_NAME_5,'".$select_result_5"');
Upvotes: 1
Reputation: 838416
You can build your query dynamically, something like this:
$sql = "SELECT ... FROM ... WHERE 1=1 ";
if ($manufacturer != "") {
$sql .= " AND manufacturer = ...";
}
if ($computerType != "") {
$sql .= " AND computerType = ...";
}
// etc...
Upvotes: 2