I need to know if there’s a more efficient way to do a search when a user leaves a blank field
<select name="department"> <option value="">Select Department</option> <option value="value1">Value1</option> <option value="value2">Value2</option> </select> <select name="course"> <option value="">Select Course</option> <option value="value1">Value1</option> <option value="value2">Value2</option> </select>
My question is how do I do this? My own conclusion was to use a variety of
if(isset($_GET['dept']) && !isset)
and so on then corresponding each with its own SELECT * FROM....
but this seems so bothersome and not that dynamic especially if I decided to add a third or fourth field and it’ll be a whole new additional set of ifs.
Is there a more efficient way to do this?
Perhaps in MySQL?
Advertisement
Answer
Like I said in the comments section, I don’t know if this is more efficient, but I think it’s easier to read and will help ease the pain of changing all conditions of your statement. I did not find tutorials about things like that, but here’s a modified example of something I’ve done in the past for a real estate company:
if(isset($_POST['search'])){ $prov_query = ''; $city_query = ''; $build_query = ''; $trans_query = ''; $amb_query = ''; $prov = $_POST['province']; $city = $_POST['city']; $build = $_POST['building']; $trans = $_POST['transaction']; $amb = $_POST['amb']; if($prov != ''){ $prov_query = "`province`='$prov'"; } if($city != ''){ $city_query = "`city`='$city'"; } if($build != '' && $build != '0'){ $build_query = "AND `building`='$build'"; } if($trans != '' && $trans != '0'){ $trans_query = "AND `transaction`='$trans'"; } if($amb != ''){ if($amb == 5){ $amb_query = "`amb`>='5'"; } else { $amb_query = "`amb`='$amb'"; } } $full_search_query = "SELECT * FROM `properties` WHERE $prov_query AND $city_query $build_query $trans_query AND $amb_query ORDER BY `id` DESC"; }
Please note, for search engines, you might want to use
"`column` LIKE '%$value%'"
or something similar as your SQL query, but my example required exact matches.
This has a few requirement tweaks, your conditionals will definitely be different than these, but I just want to share the idea. You see, all you have to do if you want to add more options (columns) is add a set of if
‘s that match your requirement and then accordingly add the variable to the final string. Hope this helps at least a little.