« Upgrade Mac OSX to Leopard, Web Server Apache httpd config lost | Main | More PHP sample and demonstration programs »

November 30, 2007

Easy selection of multiple SQL conditions from PHP

Are 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

Posted by gje at November 30, 2007 08:41 AM

Comments

Post a comment

! Comment registration is required but no TypeKey token has been given in weblog configuration!
Well House Consultants Ltd. Copyright 2008