Page 1 of 1

FOREACH in search query

Posted: Sat May 06, 2006 11:17 am
by sunnydayz
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

Code: Select all

$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!!

Posted: Sat May 06, 2006 11:31 am
by feyd
make sure the element (select tag) is named with "[]" on the end of it and php will automatically create an array out of it making looping over it much easier. For instance "horse_sex[]" would be available as $_GET['horse_sex'] or $_POST['horse_sex'] depending on your submission method.

Once you get the array being submitted correctly, use something like this

Code: Select all

$horse_sex = array_unique($_GET['horse_sex']);
$sexes = array('Gelding', 'Mare', 'Stallion');
$add = array();
foreach($horse_sex as $sex)
{
  if(array_search($sex, $sexes) !== false))
  {
    $add[] = mysql_real_escape_string($sex);
  }
}
if(count($add) > 0)
{
  $add = '`horse_sex = \'' . implode('\' OR `horse_sex` = \'', $add) . '\'';
}
else
{
  $add = '';
}
$sql .= $add;