homepage Welcome to WebmasterWorld Guest from 54.227.67.210
register, free tools, login, search, subscribe, help, library, announcements, recent posts, open posts,
Subscribe to WebmasterWorld
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
Selecting records from database
Only if matching variables are populated
PumpkinHead




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

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

 

dcrombie




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

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 ;)

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved