Optional search criteria

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
hame22
Forum Contributor
Posts: 214
Joined: Wed May 11, 2005 5:50 am

Optional search criteria

Post 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
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post 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;
Post Reply