Jump to content

[SOLVED] Search using multiple select boxes


tommyda

Recommended Posts

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.

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]

 

 

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.