lional Posted January 21, 2009 Share Posted January 21, 2009 Hi All Got a quick question I am writing a series of options that will end up pulling the search from a mysql table. I have three options provinces, city, suburb where there is an all option for each of these relating to the previous selection. I could however end up where province could either be all or a provinces, city could ne all or a city and suburb could be all or a city. If I want to run a query based on these conditions what would be the easiest conditional. there could be 9 if statements for the following: province city suburb all all all all all suburb all city all do I need to do 9 conditions or is there a shorter form to do the query I hope the above is clear Thanks Lional Quote Link to comment Share on other sites More sharing options...
MatthewJ Posted January 21, 2009 Share Posted January 21, 2009 You would just build the query based on the choices "SELECT * FROM table WHERE province = '%".mysql_real_escape_string($_POST['province'])."%' AND city = '%".mysql_real_escape_string($_POST['city'])."%'" AND suburb = '%".mysql_real_escape_string($_POST['suburb'])."%'"; Quote Link to comment Share on other sites More sharing options...
lional Posted January 21, 2009 Author Share Posted January 21, 2009 That would work fine but if the user selects the all for any of the sections how will I include this into my query Quote Link to comment Share on other sites More sharing options...
Psycho Posted January 21, 2009 Share Posted January 21, 2009 if($_POST['province']!='all') { $whereList[] = "province = '".mysql_real_escape_string($_POST['province'])."'"; } if($_POST['city']!='all') { $whereList[] = "city = '".mysql_real_escape_string($_POST['city'])."'"; } if($_POST['suburb']!='all') { $whereList[] = "suburb = '".mysql_real_escape_string($_POST['suburb'])."'"; } $whereClause = (count($whereList)) ? ' WHERE ' . implode(' OR ', $whereList) : ''; $query = "SELECT * FROM table $whereClause"; Quote Link to comment Share on other sites More sharing options...
MatthewJ Posted January 21, 2009 Share Posted January 21, 2009 Maybe I am misunderstanding, but if you selected all, you would just pass a blank value... The resulting would be ...AND field = '%%' which would match anything. so If I chose 1 province, all cities, and all suburbs, a query might look like "SELECT * FROM table WHERE province = '%selectedprovince%' AND city = '%%' AND suburb = '%%'"; mjdamato's code will do the same thing, without the use of wildcards... definately the better way to go. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.