Jump to content

PHP, MySQL - select where nothing


rtpmatt

Recommended Posts

Hi, I am wondering what the best way to search my DB is when there are multiple search possibilities.

say, a user has the option of searching by name, or by price.  if they enter a name, but no price, is there a way to use one SELECT statement?

 

such as:

$searchName="name to search for";

$searchPrice="";

"SELECT item FROM productList WHERE name='$searchName' && price='$searchPrice'";

 

is there something I can set $searchPrice to so that it will return true for every price?

 

Im sure this is easy, but i have tryed several things and i haven't found it yet

thanks

 

-matt

Link to comment
https://forums.phpfreaks.com/topic/44561-php-mysql-select-where-nothing/
Share on other sites

Not sure if this is what you want, but this is what I would do in order to search by one, the other, or both.

 


// Just to show you in a little more detailed, not sure how you are getting your variables
$searchName = $_GET[byname];
$searchPrice = $_GET[byprice];

// Will search for both IF both are given
if($searchName && $searchPrice)  {
$sql = "SELECT item FROM productList WHERE name='$searchName' AND price='$searchPrice'";
}
// Will only search by name IF the above does not work
if(!$sql && $searchName)  {
$sql = "SELECT item FROM productList WHERE name='$searchName'";
}
// Will only search by price IF the two above don't work
if(!$sql && $searchPrice)  {
$sql = "SELECT item FROM productList WHERE price='$searchPrice'";
}

// Will search for both IF both are true
if($searchName && $searchPrice)  {
$sql = "SELECT item FROM productList WHERE name='$searchName' AND price='$searchPrice'";
}

//Will search for only one if true
if($searchName || $searchPrice)  {
$sql = "SELECT item FROM productList WHERE name='$searchName' AND price='$searchPrice'";
}


Thanks I am able to get those working, the || seems to be what I am looking for...is there an easier way than multiple ifs when i have more than 2 WHEREs though?

such as:

 

"SELECT item FROM productList WHERE name='$searchName' && price='$searchPrice' && weight='$searchWeight'";

 

using multiple ifs is working for the moment, but it doesn't seem very clean.  Basically I always want it to be && UNLESS one of the terms is empty, in which case i want that term ignored.

i was wondering if there was something i could set one of the values to so that it will always return true.  The more WHEREs I have the uglier the ifs get.

 

thanks for the help

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.