Page 1 of 1

Searching on multiple fields...

Posted: Thu Jun 09, 2005 10:01 am
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!

Posted: Thu Jun 09, 2005 10:52 am
by anjanesh

Code: Select all

$res = mysql_query("DESCRIBE `tablename`");
while ($row = mysql_fetch_assoc($res))
 {
    $arr[] = $row['Field']; // Store your fieldnames
 }

Posted: Thu Jun 09, 2005 11:07 am
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());

Posted: Thu Jun 09, 2005 11:38 am
by dardsemail
Thanks so much... I'll give it a shot!