Sikander Sikander - 5 months ago 9x
SQL Question

Sql : Update sql query on the basis of posted values

i am doing a query on the basis of posted values for eg. following is the query

$query= mysqli_query($connect,
"SELECT * FROM residential WHERE type='$type' AND unit_type='$unit_type' "
. "AND price BETWEEN '$min_price' AND '$max_price' "
. " AND bedrooms BETWEEN '$min_bedrooms' AND '$max_bedrooms'");

$unit_type , $min_price etc are coming from $_POST array
, my problem is that if i don't receive any of the used values
($type ,$max_bedrooms, $min_bedrooms etc )
in query, then query does not work. my question is how do i update the query on the basis of only posted values .


Use a $query variable and change it by your post values

$query= "SELECT * FROM residential  WHERE 1=1 "; 
 $query.=" AND  type='$type'";
 $query.=" AND  unit_type='$unit_type'";
if(($min_price!="") && ($max_price!="")){
 $query.=" AND  price BETWEEN '$min_price' AND '$max_price' ";
if(($min_bedrooms!="") && ($max_bedrooms!="")){
 $query.=" AND bedrooms BETWEEN '$min_bedrooms' AND '$max_bedrooms'";
$result= mysqli_query($connect,$query);