tommyda Posted November 5, 2009 Share Posted November 5, 2009 I am creating a search function for a customer database and have four <select> boxes with search values. I would like the user to be able to choose one or more of the options and search the database. I started writing the following code but if I carry on it will take a long time and im sure there must be a way of using .= or something similar to get the job done. if (isset($_POST['archiveoption']) && !isset($_POST['deliveryoption']) && !isset($_POST['paymentoption']) && !isset($_POST['status'])) { $query = "SELECT * FROM customers WHERE archiveoption='$_POST[archiveoption]'"; } if (isset($_POST['archiveoption']) && isset($_POST['deliveryoption']) && !isset($_POST['paymentoption']) && !isset($_POST['status'])) { $query = "SELECT * FROM customers WHERE archiveoption='$_POST[archiveoption]' AND deliveryoption='$_POST[deliveryoption]'"; } if (isset($_POST['archiveoption']) && !isset($_POST['deliveryoption']) && isset($_POST['paymentoption']) && !isset($_POST['status'])) { $query = "SELECT * FROM customers WHERE archiveoption='$_POST[archiveoption]' AND deliveryoption='$_POST[deliveryoption]'"; } I thought I could use something like if(isset($_POST['archiveoption'])) {$query .= "AND archiveoption='$_POST[archiveoption]'"}; if(isset($_POST['deliveryoption'])) {$query .= "AND deliveryoption='$_POST[deliveryoption]'"}; etc... The problem im having is that if there is only one box selected the query has "AND ..." which wont work. Please if anyone can help me out i would appreciate it very much. Link to comment https://forums.phpfreaks.com/topic/180352-solved-search-using-multiple-select-boxes/ Share on other sites More sharing options...
gizmola Posted November 5, 2009 Share Posted November 5, 2009 You are on the right track. Simply have a counter variable that you initialize to 0, and check that out to determine whether or not you need to preface your WHERE clause criteria with an 'AND'. $critCount = 0; // Number of criteria if(isset($_POST['archiveoption'])) { if ($critCount > 0) { $query .= ' AND'; } $query .= " archiveoption='$_POST[archiveoption]'"; $critCount++; }; etc... This way, once the first criteria is added to the WHERE clause, any subsequent criteria will be added using the AND. [/code] Link to comment https://forums.phpfreaks.com/topic/180352-solved-search-using-multiple-select-boxes/#findComment-951405 Share on other sites More sharing options...
tommyda Posted November 5, 2009 Author Share Posted November 5, 2009 Thanks man I should have thought of that. Link to comment https://forums.phpfreaks.com/topic/180352-solved-search-using-multiple-select-boxes/#findComment-951430 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.