Welcome to WebmasterWorld Guest from 54.167.157.247

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Selecting records from database

Only if matching variables are populated

   
11:23 am on Sep 8, 2005 (gmt 0)

10+ Year Member



Hi all,

I'm creating a user lookup system where a visitor populates a form with all the information that they have on a user.

Form
----

First Name ($form_fname)
Surname ($form_sname)
Location ($form_locatn)
Extension Number ($form_extn)

There are no required fields in the above form, the user simply enters all the information they have to shorten the list.

I need to do a select from the database, but only on fields that have been populated. Obviously, doing the following would be wrong/stupid/dumb etc:

if ($form_fname!="")
{ $query = "SELECT * FROM MYDATABASE WHERE db_fname ='$form_fname'";}
if ($form_fname!="" AND $form_sname)
{ $query = "SELECT * FROM MYDATABASE WHERE db_fname ='$form_fname' AND db_sname='$form_sname'";}
...
if ($form_fname!="" AND $form_sname!="" AND $form_locatn!="" AND $form_extn!="")
{ $query = "SELECT * FROM MYDATABASE WHERE db_fname ='$form_fname' AND db_surname='$form_sname' AND db_location='$form_locatn'"; AND db_extn='$form_extn'";}
etc

Could someone advise the best way of doing this? Should I move everything into an array and remove records as I go along?

Cheers :x

11:52 am on Sep 8, 2005 (gmt 0)

10+ Year Member



Here's how I would start:

$WHERE = array(); 
if($firstname) $WHERE[] = "firstname='$firstname'";
if($lastname) $WHERE[] = "lastname='$lastname'";
...

and then:

$query = "SELECT * FROM table"; 
if($WHERE) $query .= " WHERE " . implode(" AND ", $WHERE);

Hope that helps ;)