Articles

Database queries

When filtering results from a database you can often get in a mess building the database queries.

The nicest way I've found to build the queries is to add each filter to an array like so:

$name_search = 'John';
$address_search = 'UK';
 
$query = 'SELECT * FROM people';
 
if ($name_search!='')
    $wheres[] = ' name LIKE "%'.$name_search.'%"';
if ($address_search)
    $wheres[] = ' address LIKE "%'.$address_search.'%"';
 
$query .= (count($wheres)>0 ? ' WHERE '.implode(' AND ', $wheres) : '');
 

You would of course be escaping the data etc. for the database you are using. Never trust the input.