Forum Moderators: coopster
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
$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 ;)