April 23, 2012

how to change variable when filter is on

Question by bonny

hello i would like to code a filter for an search engine on my site. now i thought it would be the best way to use a simple filter. so my code looks like:

}else if ($filter_a === 1){
        $filter = "WHERE `a` LIKE '%$a%'";
}else if ($filter_b === 1){
        $filter = "WHERE `b` LIKE '%$b%'";
}else if ($filter_c === 1){
        $filter = "WHERE `c` LIKE '%$c%'";
}else if ( ($filter_a === 1) && ($filter_b === 1) ){
        $filter = "WHERE `a` LIKE '%$a%' AND `b` LIKE '%$b%'";
}else if ( ($filter_a === 1) && ($filter_c === 1) ){
        $filter = "WHERE `a` LIKE '%$a%' AND `c` LIKE '%$c%'";
... and so on

the problem is that i have 5x N so the permutation of this would be 120 possibilites for $filter

is there a way how i can solve this? if there is someone who could help me out i really would appreciate. thanks a lot.

Answer by Starx

How about this way?

if ($filter_a === 1) {
        $filter[] = "`a` LIKE '%$a%'";
if ($filter_b === 1) {
        $filter[] = "`b` LIKE '%$b%'";
if ($filter_c === 1) {
        $filter[] = "`c` LIKE '%$c%'";
$filter = "WHERE ".implode(" AND ", $filter);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!