I've got a search form and on one of the select fields I have the "multiple" option set. For my example, I'm using horse gender. When someone selects "mare", I want all the db entries with mare to show up. When someone selects both "mare" and "stallion" I want all of the mare and stallion entries to show up.

Current php code

 $sex = $_GET['horse_sex'];
$sexes = array('Gelding', 'Mare', 'Stallion');
if(strlen($sex) > 0){
    if($state1 OR $state2 OR $state3 OR $state4) $sql .= " AND";
    foreach($sexes as $sex)
{
    $sql .= " horse_sex = '$sex' OR";
}
    $sql = rtrim($sql, "OR");
    $state5 = true;
} 

The problem right now is that when I select one item, it shows the results as if I selected all 3 items. If I select 2 items, it again shows me results for all 3, even though all 3 items are not in the $_GET variable in the URL.

How do I just get it to search for the items that were selected. I've been working on this problem for a couple days now, and I've gotten a little further along, but this is really stumping me. Please help!!

    Instead of writing it as: x=a OR x=b OR x=c
    Write it as: x IN (a, b, c)

    $sexes = array('Gelding', 'Mare', 'Stallion');
    // check that all elements in $_GET['horse_sex'] are in $sexes
    if (count(array_diff($_GET['horse_sex'], $sexes)) == 0) {
    	$sql .= " AND horse_sex IN ('" . implode("','", $_GET['horse_sex']) . "')";
    }

      You are a life saver! I got that to work. Thank you sooo much!

        Write a Reply...