help writing a code to search filled-in paramaters only

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
adamgram
Forum Newbie
Posts: 1
Joined: Sun Sep 07, 2008 9:52 am

help writing a code to search filled-in paramaters only

Post by adamgram »

So I'm very new to all this and I'm trying to build a website based on a MySQL database. I want to make a page that has a bunch of different paramaters you can search by. The way it's set up now if you don't fill out a certain criteria it only turns up entries where that criteria is blank. I want it to show all of the rows where the other columns match, ignoring the blank one. Here's what I'm doing now:

$result = mysql_query("SELECT * FROM table
WHERE var_1='$var_1'
AND var_2='$var_2'
AND var_3='$var_3'
");

$var_1, $var_2, and $var_3 all come from an html form, and if certain fields aren't filled in the variables are left blank and respond to if... statement where $var_1=='' When I only had 4 paramaters I made one for each of the 16 possible combinations, but now I want to do 9 so I think it's time to figure out a better way. I've been searching for a couple hours but it seems like I don't know enough about MySQL to know what to look for. I just copied what I have now from a tutorial. Anyone one to help point me in the right direction? Thanks in advance!
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: help writing a code to search filled-in paramaters only

Post by andyhoneycutt »

You could use a foreach on your $_POST:

Code: Select all

$add_where = "";
foreach($_POST as $key => $value)
{
  if( $value != "" )
    $add_where .= "$key = '" . mysql_real_escape_string($value) . "' AND ";
}
$add_where = substr($add_where,0,strlen($add_where)-4); // trim off the training "AND "
User avatar
andyhoneycutt
Forum Contributor
Posts: 468
Joined: Wed Aug 27, 2008 10:02 am
Location: Idaho Falls

Re: help writing a code to search filled-in paramaters only

Post by andyhoneycutt »

Sorry, it's early, you'll want a mysql_real_escape_string on your $key as well.

-Andy
Post Reply