Page 1 of 1

Optional search criteria

Posted: Wed May 11, 2005 5:54 am
by hame22
Hey all

I am setting up a search form that allows a user to search a library based upon a number of search criteria, e.g. author, title, cost, date etc

I can easily search one field or all the fields at once, but what i want to allow the user to do is have the option of searching from a pick of the fields, meaning each criteria on the search form is optional.

Basically it will mean that what fields the user selects will be searched for, so a user could look for a book based on its price and author.

i hope this is understandable

any ideas??

thanks alex

Posted: Wed May 11, 2005 6:38 am
by John Cartwright
Basically, you will have to build your query depending on which post fields have been submitted.

Code: Select all

$post = array('title','price','author','published');
$count = count($post);
$sql = &quote;SELECT * FROM `books` WHERE &quote;;

$i = 0;
foreach ($post as $new_post)
{
     $i ++;
     //never be ashamed of being paranoid
     //only accept specific fields
     //check the string to make sure it is valid
     if (!empty($_POSTї&quote;$new_post&quote;]) && validate_string($_POSTї&quote;$new_post&quote;])
     {
          $sql .= &quote;`$new_post` LIKE '%&quote;.$_POSTї&quote;new_post&quote;].&quote;%'&quote;;
          $sql .= ($count == $i ? '' : ' OR ');
     }
}

echo $sql;