对数组进行排序并将AND添加到查询中

hello i like to code a filter for my search engine. i have some problems with the different select queries. so the main idea is that i have some inputfields with checkboxes like:

inputfield a: [_] filter on/off: [ ]

inputfield b: [_] filter on/off: [ ]

inputfield c: [_] filter on/off: [ ]

to set the query i have named the query for each field:

if ($filter_a == true) {
        $filter_1 =" `a` LIKE '%$input_a%' ";
    }

if ($filter_b == true) {
        $filter_2 =" `b` LIKE '%$input_b%' ";
    }

if ($filter_c == true) {
        $filter_3 =" `c` LIKE '%$input_c%' ";
    }

so in case of an enabled filter the select query should change in a specific way like:

in case of enabled filter_a:

$query = "SELECT `a`, `b`, `c` FROM `table` WHERE $filter_a";

in case of enabled filter_a AND filter_b:

$query = "SELECT `a`, `b`, `c` FROM `table` WHERE $filter_a AND filter_b";

in case of enabled filter_a AND filter_b AND filter_c:

$query = "SELECT `a`, `b`, `c` FROM `table` WHERE $filter_a AND filter_b AND filter_c";

i'm having problems with adding "AND" to the queries. therfor i have integrated a counter that counts how many filters are set:

$counter = 0;
...
if(!empty($_POST['input_a']) && (!empty($_POST['checkbox_filter_1'])) ){
        $filter++;
}
...

if ($counter == 2) {
$and1 = " AND ";
     $query = "SELECT `a`, `b`, `c` FROM `table` WHERE $filter_a $and1 filter_b";
}

so the main problem is permutation. up to this point i have 5 filters what means there are 125 possibilites to compare with.

so my next idea would be to create an array with each query and order them.

so it should look like:

$ordered_query = (
1-> `a` LIKE '%$input_a%',
2-> `b` LIKE '%$input_b%',
3-> `c` LIKE '%$input_c%');

so that i have all queries in one array. the next step should be to order them regarding the filters who are set or not.

so in case of enabling filter_3 and filter_1 it should order the array keys:

$ordered_query = ( 1-> input_a 2-> input_c );

and the query should automaticallyadd AND between them. in case of all enabled filter there have to be 2 AND`s between.

if there is someone who could help me out i really i would appreciate.

thanks a lot.

You should put all conditions in an array and use function implode:

$conditions = array();
$conditions[] = " `a` LIKE '%$input_a%' ";
$conditions[] = " `b` LIKE '%$input_b%' ";
// ...
$query = "SELECT ... WHERE ".implode(" AND ", $conditions);

Don't set individual $filter_1, $filter_2, and so on variables but one array for the where part.

$where = array();
if ($filter_a == true) {
    $where[] =" `a` LIKE '%$input_a%' ";
}

if ($filter_b == true) {
    $where[] =" `b` LIKE '%$input_b%' ";
}

if ($filter_c == true) {
    $where[] =" `c` LIKE '%$input_c%' ";
}

$query = "SELECT `a`, `b`, `c` FROM `table`";
if ( !empty($where) ) {
  $query .= " WHERE " . implode(' AND ', $where);
}