cparekh Posted April 10, 2008 Share Posted April 10, 2008 Hi, I'm writing a search script that takes up to 6 different fields as criteria and depending on the combination of variables queries the database. I'd like to know if there is a way to write this type of script in a more manageable way - the way I'm writing it (below) seems redundant and highly prone to errors. Here's what I've done so far (only just started): if isset($_POST['btn']) //if the form is submitted, get the 'post' variables { $seniority = $_POST['seniority']; $responsibility = $_POST['responsibility']; $interest = $_POST['interest']; $org = $_POST['org']; $contact = $_POST['contact']; $job = $_POST['job']; if (($seniority != '') && ($responsibility != '') && ($org != '') && ($contact != '') && ($job != '') ) {/*sql code here*/} //all fields are filled in else if (($seniority == '') && ($responsibility != '') && ($org != '') && ($contact != '') && ($job != '') ) {/*sql code here*/} //all fields except 'seniority' are filled in else if (($seniority != '') && ($responsibility == '') && ($org != '') && ($contact != '') && ($job != '') ) {/*sql code here*/} //all fields except 'responsibility' are filled in else if (($seniority != '') && ($responsibility != '') && ($org == '') && ($contact != '') && ($job != '') ) {/*sql code here*/} //all fields except 'org' are filled in else if (($seniority != '') && ($responsibility != '') && ($org != '') && ($contact == '') && ($job != '') ) {/*sql code here*/} //all fields except 'contact' are filled in else if (($seniority != '') && ($responsibility != '') && ($org != '') && ($contact != '') && ($job == '') ) {/*sql code here*/} //all fields except 'job' are filled in etc... Is there a way to do this more succinctly so I don't end up writing something like 12 code blocks? Any help is greatly appreciated. C. Link to comment https://forums.phpfreaks.com/topic/100456-advanced-search-writing-more-manageable-code/ Share on other sites More sharing options...
marcus Posted April 10, 2008 Share Posted April 10, 2008 Yes. You can start off with $sql = "SELECT * FROM `table`"; Then check if the variables exist, if they do continue to add onto the variable. if($onepost){ if($and == 0){ $sql .= " WHERE"; } $sql .= " `onepost` ='".$onepost."'"; $and = 1; } // and so forth Link to comment https://forums.phpfreaks.com/topic/100456-advanced-search-writing-more-manageable-code/#findComment-513737 Share on other sites More sharing options...
cparekh Posted April 11, 2008 Author Share Posted April 11, 2008 Hi, thanx for that - that should make my sql blocks a lot leaner. Nice one! Link to comment https://forums.phpfreaks.com/topic/100456-advanced-search-writing-more-manageable-code/#findComment-514540 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.