Easy selection of multiple SQL conditions from PHP
Archive - Originally posted on "The Horse's Mouth" - 2007-11-30 08:41:36 - Graham EllisAre you automating an SQL query in a web page, wanting to select records to display only where they match a whole series of criteria from what could be a long list of options - for example looking for houses:
* Only in Melksham
* Less that 200k
* With a large garden
and other criteria that perhaps are required by other users might include:
* Near a good school
* Near public transport
* Ground floor
* Parking
If all that data is in your database - good, you can do it. But how do you build up the complex query? One useful trick is to have an array of possible queries, then push all the ones that you actually want into a further array and link them together with an implode putting an " and" between each element ..
$selectors = array(
"cheap" => "asking < 200000",
"local" => 'locate = "Melksham"',
 "bathphone" => 'phone like "01225%"');
$cwant = array();
foreach (array_keys($selectors) as $cdi) {
if ($_GET[$cdi]) {
array_push($cwant, $selectors[$cdi]);
}
}
$restrict = implode (" and ",$cwant);
Demo here
Full source code here