Jump to content

Advanced Search - writing more manageable code


cparekh

Recommended Posts

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. 

 

 

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.