Sikander Sikander - 7 months ago 11
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'");


now
$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 .

Answer

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

$query= "SELECT * FROM residential  WHERE 1=1 "; 
if($type!=""){
 $query.=" AND  type='$type'";
}
if($unit_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);
Comments