Searching on multiple fields...

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Searching on multiple fields...

Post by dardsemail »

Hi,

I've done some research on searching a db on multiple fields - but I'm kind of coming up blank on this one though, admittedly, its a very common and straightforward task.

I have a search form for a user to complete with multiple fields listed based on what is listed in the db table. I'd like to be able to pull from those fields to generate a query - but would like to have those fields for which the user has NOT selected anything ignored in the query. I don't know why - but I'm stuck.

So if I have $_POST['fieldOne'] and $_POST['fieldTwo'] I would like to be able to dynamically generate a query that would examine whether or not $_POST['fieldOne'] is emptyand then examine the same for $_POST'fieldTwo'].

Then, the query would dynamically be generated based on selecting the fields in which the values were not null.

If anyone can point me in the right direction regarding a tutorial or something of that nature... I would be greatly appreciative :-)

Thanks in advance!
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post by anjanesh »

Code: Select all

$res = mysql_query("DESCRIBE `tablename`");
while ($row = mysql_fetch_assoc($res))
 {
    $arr[] = $row['Field']; // Store your fieldnames
 }
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Post by Burrito »

Code: Select all

$query = "select * from myTable where 1";
$query .= ($_POST['field1'] !== '' ? " and field1 = '".$_POST['field1']."'" : "");
$query .= ($_POST['field2'] !== '' ? " and field2 = '".$_POST['field2']."'" : "");
mysql_query($query)
  or die(mysql_error());
dardsemail
Forum Contributor
Posts: 136
Joined: Thu Jun 03, 2004 9:02 pm

Post by dardsemail »

Thanks so much... I'll give it a shot!
Post Reply