简体   繁体   中英

How to implement multiple search filters in php

I m trying to implement filters in php and mysql to search record in database....Filters should be like if among 6 filters only two is selected query will perform "AND" operation for these two and fetch data from database and if three then it will perform "AND" operation for these three filters..... one way to implement is to check for each filter like.

if (isset($_GET['name'] && isset($_GET['city'])) { 
    // perform AND for these two
} elseif(isset($_GET['name'] && (isset($_GET['age'])) {
    // perform AND for these three
}

// and so on ...

But the problem is if i have 6 filters then i have to create 64 combinations for it... I m thinking about that is there any alternative solution exists for it?

This could work, assuming that your $_GET keys match columns in your table:

$query = "SELECT * FROM table";

$filtered_get = array_filter($_GET); // removes empty values from $_GET

if (count($filtered_get)) { // not empty
    $query .= " WHERE";

    $keynames = array_keys($filtered_get); // make array of key names from $filtered_get

    foreach($filtered_get as $key => $value)
    {
       $query .= " $keynames[$key] = '$value'";  // $filtered_get keyname = $filtered_get['keyname'] value
       if (count($filtered_get) > 1 && (count($filtered_get) > $key)) { // more than one search filter, and not the last
          $query .= " AND";
       }
    }
}
$query .= ";"

$query = "SELECT * FROM table WHERE name = 'name' AND city = 'city' AND age = 'age';"

I think this may work, although this code sample does not include sanitization against SQL injection, so you should probably add something to scrub potentially dangerous input

Updated : added $filtered_get = array_filter($_GET); to filter out any empty fields from $_GET array

single if condition to check value is empty or not.for non-empty then mysql query is two between 'AND' operation.
$query = 'select * from info';
$where = ' Where';
$and = 'id = 1';
if(!empty($_GET['name'])){
  $and .= ' AND name="test"';
}
if(!empty($_GET['city'])){
  $and .= ' AND city="test"';
}
$q = $query.''.$where.''.$and;
make like this query is 'select & from info where id=1 AND name="test" AND city="test"';

You can use a prefix for the form elements, like filter-, so items will look like filter-age, filter-name and so on. Now, let's suppose you have a function like

function buildFilters($input, $delimiter) {
    foreach ($input as $key => $value) {
        $filters = array();
        $filters[]="1=1";//default filter
        if (strpos($key, $prefix) === 0) {
            //add the filter to $filters via $filters[]=yourvalue
        }
    }
    return implode($delimiter, $filters);
}

and then you can call it like

$myFilters = buildFilters($_POST, " AND ");

I tried using the answer from @tshimkus. Maybe it's the way I have the arrays set up or something but there were a couple problems I ran into before getting it to work.

this line:

$query .= " $keynames[$key] = '$value'";

for me needed to be:

$query .= " $key = '$value'";

I also didn't get the check (shown below) for last item to work.

if (count($filtered_get) > 1 && (count($filtered_get) > $key)) { // more than one search filter, and not the last

ended up using a count along with this instead:

if($i!==$len){
$whereClause = '  ';
  
    if ( !empty($_POST['gender']) || !empty($_POST['hobby']) || !empty($_POST['search_filter']) ) {
    
    $whereClause .= ' WHERE ';
    if ( !empty($_POST['gender']) && !empty($_POST['hobby']) && !empty($_POST['search_filter']) ) {
        $whereClause .= ' gender = "'.$_POST['gender'].'" AND gender = "'.$_POST['gender'].'" AND search_filter LIKE "%'.$_POST['search_filter'].'%" ';

    } else {

        if ( !empty($_POST['gender']) && $_POST['gender'] != "" && empty($_POST['hobby']) && empty($_POST['search_filter']) ) {
            $whereClause .= ' gender = "'.$_POST['gender'].'"  ';          
        }
        else if ( (!empty($_POST['gender']) && $_POST['gender'] != "") &&  (!empty($_POST['hobby']) || !empty($_POST['search_filter']))) {
            $whereClause .= ' gender = "'.$_POST['gender'].'"  '; 
            $whereClause .= ' AND ';
        }
        
        if ( !empty($_POST['hobby']) && $_POST['hobby'] != "" && empty($_POST['gender']) && empty($_POST['name'])){
            $whereClause .= ' hobby = "'.$_POST['hobby'].'"  ';           
        }
        else if ( (!empty($_POST['hobby']) && $_POST['hobby'] != "") &&  (!empty($_POST['gender']) || !empty($_POST['search_filter']))) {
            $whereClause .= ' hobby = "'.$_POST['hobby'].'"  '; 
            $whereClause .= ' AND ';
        } 
        
        if ( !empty($_POST['search_filter'])) {
            $whereClause .= ' search_filter LIKE "%'.$_POST['search_filter'].'%"  ';       
        }    
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM