Joomla modules and resources
Articles
Database queries
- Details
- Published on Tuesday, 26 July 2011 12:35
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.