Hi I've set up a website which gathers results from a mysql database which allows the user to sort the results according to some preferences in 2 separate select lists.

It works as long as you make a selection from both boxes before submitting.

I would like for results to be shown if the user makes a selection from only one of the lists.

This is the code I am using right now; I can see why it only displays results if all menus have selected options but haven't a clue how to alter it to do as I wish.


FROM inventory
WHERE bedrooms like '$bedrooms' AND bathrooms like '$bathrooms'
ORDER BY model_name ASC";

Can anyone help me out?


if(isset($_POST['bedrooms']) && isset($_POST['bathrooms']) )
    $condition=" where bedrooms like '{$_POST['bedrooms']}' AND bathrooms like '{$_POST['bathrooms']}' "; 
elseif(!isset($_POST['bedrooms']) && isset($_POST['bathrooms']) )
    $condition=" where bathrooms like  '{$_POST['bathrooms']}' "; 
elseif(isset($_POST['bedrooms']) && !isset($_POST['bathrooms']) )
    $condition=" where bedrooms like '{$_POST['bedrooms']}' "; 

$query= "SELECT * FROM inventory {$condition} ORDER BY model_name ASC";

Thanks urtrivedi,

I tried out your code, and it unfortunately didn't display any results when only one selection was made.

try this code.

$whereStr = ' 1=1 ';
if(trim($bedrooms)!='') $whereStr.= " AND  bedrooms like '$bedrooms'" ;
if(trim($bathrooms)!='') $whereStr.= " AND  bathrooms like '$bathrooms'" ;
$query=   "SELECT * FROM inventory WHERE ".$whereStr." ORDER BY model_name ASC";

Ya you may also use code posted by vibhadevit.

Thanks vibhadevit that solved the issue!