简体   繁体   中英

Writing a search filter — filter at the SQL level or PHP level?

I have an ajax filter on a search page that filters teacher results based on a set of criteria that can be manipulated by the user. I'm trying to decide whether to

1) first go get all the teachers data, then in PHP make a new array of just those teachers who aren't affected by the negative filters

or

2) build an sql query with a number of WHERE clauses, ie 'WHERE pay = $pay && city = $city && distance < $distance".

Part of me thinks that number 2 might be a better option, but I'm already unsure of how to fill the query's variable values when the user hasn't specified a certain filter. So, for example, if $pay is undefined, the query will fail. in this case, what I would like to do is query teachers regardless of their pay.

For the SQL approach, you should build your query based on whether or not the inputs are empty

Something like

$sql = 'SELECT * FROM Teachers';
$filter = array();
if (!empty($pay)) $filter[] = 'pay = "'.$pay.'"';
if (!empty($city)) $filter[] = 'city = "'.$city.'"';
if (!empty($city)) $filter[] = 'distance < "'.$distance.'"';

if (!empty($filter)) {
    $and = ' WHERE';
    foreach ($filter as $f) {
        $sql .= $and.' '.$f;
        $and = ' AND';
    }
}

Mind you, you should be concerned about SQL injection since this is just a simple demonstration.

If you don't have a lot of teachers in the database you can fetch all of them and handle it in PHP as you suggested.

If you don't want to fetch a lot of data you can go with the second option. In that case you might want to build a dynamic query.

for example:

$payCond = "";

... 

if (isset($pay) && $pay != ""){
    if ($payCond != ""){
        $payCond .= "And ";
    }
    $payCond = "pay=" . intval($pay);
}

Query as close to the database as possible. That said, you can use vacuous expressions to simplify code:

$payExpr = (isset($_REQUEST['pay']) ? 'pay='.$_REQUEST['pay'] : '1=1');
$query = "select * from Foo where $payExpr";

The secret sauce here is using '1=1' when pay not given. However, there is still more you need to do that I'm skipping in this quick example, like avoiding sql injection with bound parameters. Caveat emptor: I havent compiled this code, as I am pecking on a tablet!

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