red one
red one

Reputation: 182

making a better search query in php and mysql

I'm trying to create a search query:

I'm giving 6 options to search.

  1. Bedrooms
  2. Type
  3. Postcode
  4. Location
  5. Min price
  6. Max price

I have these fields in a form. I searched a lot but couldn't find the answer I was searching. I tried queries using LIKE and % too. But that didn't worked out too.

If a user selects only 'Type' then all of the data with that type should be displayed. And the same goes to other fields.

And again, if a user selects 2 or 3 options and searches then the results which match the options selected should be displayed.

How can I create a search like this? Should I do?:

if(){

}else if(){

}

Upvotes: 0

Views: 421

Answers (3)

liding
liding

Reputation: 116

if(!empty($some_option)) $search_options["option_name"] = $some_option;
$query = "some query";
$where = "";
if(!empty($search_options)){
    $first_option = array_shift($search_types);
    $where = " " . key($first_option) . " = " . $first_option;
    foreach($search_options as $key => $option){
        $where .= " AND $key = $option";
    }
}
$query .= $where;

Upvotes: 0

user1759572
user1759572

Reputation: 683

You can build your sql query on the fly. If search value is not empty (or something else that does not count as a search value) then do not add search. Do not forget to add mysql_real_escape_string to a params or bad people will exploit your software.

exampe in php:

<?php
$params = array('type' => 'aaa', 'max_price'=>100); // parameters that a user gave. Example from $_POST or $_GET

$querySearch = array();
if(isset($params['type'])) {
  $querySearch[] = "type LIKE '%".mysql_real_escape_string($params['type'])."%'";
}

if(isset($params['max_price'])) {
  $querySearch[] = "price <= ".mysql_real_escape_string($params['max_price']);
}       

if(isset($params['min_price'])) {
  $querySearch[] = "price >= ".mysql_real_escape_string($params['min_price']);
}

// and etc.

$q = 'select * FROM hotel WHERE ' . implode(' AND ' , $querySearch);
echo $q;
?>

then you can use query $q to do db select.

Upvotes: 1

SQL.injection
SQL.injection

Reputation: 2647

dynamically build the query

$useAnd = false;
$ query = " select * from table";
if (isset($bedrooms) == true or isset($type) == true or isset($postcode)==true or ...)
{
    $query = $query. " where "; 
    if (isset($bedroomsIsset) = true) 
    {
     $query = $query . "bedrooms >=". $bedrooms; $useAnd=true;
    }
   if (isset($type) = true) 
   {
      if ($useAnd=true)
      {$query = $query . " and " ;}
      $query = $query . "type =". $type; $useAnd=true;
    }
    if (isset($postcode)==true)
    {
   if (isset($poscode) = true) 
   {
      if ($useAnd=true)
      {$query = $query . " and " ;}
      $query = $query . "postcode =". $postcode; $useAnd=true;

    }
    if (...)

}

Upvotes: 1

Related Questions