如果mysql中的if子句选择

问题描述:

My full query is:

$sql = "SELECT vehicle_id,  fuel_type, gearbox_type, door_type, engine_package_name, FORMAT(engine_cap, 1)engine_cap, engine_power, FORMAT(fuel_cons, 1)fuel_cons, FORMAT(std_price, 0)std_price 
FROM vehicle 
WHERE model_id = '$model_id' 
AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4') AND gearbox_type IN( '$gearbox_type1', '$gearbox_type2', '$gearbox_type3', '$gearbox_type4') AND door_type IN ('$door_type1', '$door_type2', '$door_type3', '$door_type4')" ;

I would like to skip the part of the query shown below if $fuel_type1 equals to zero.

AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4') 

I have tried

$sql = "SELECT vehicle_id,  fuel_type, gearbox_type, door_type, engine_package_name, FORMAT(engine_cap, 1)engine_cap, engine_power, FORMAT(fuel_cons, 1)fuel_cons, FORMAT(std_price, 0)std_price 
FROM vehicle 
WHERE model_id = '$model_id' ";

if($fuel_type1 != 0) 
{ 
    $sql += “ AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4')”;
}

didn't worked.

Also I have tried

$sql = "SELECT vehicle_id, fuel_type, gearbox_type, door_type, engine_package_name, FORMAT(engine_cap, 1)engine_cap, engine_power, FORMAT(fuel_cons, 1)fuel_cons, FORMAT(std_price, 0)std_price 
FROM vehicle 
WHERE model_id='$model_id’ 
AND IF($fuel_type1 <> 0,'fuel_type','0') IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4’)";

didn't worked :((

any help will be appreciated.

problem is in your concatenation process

in PHP there should b a do t. to concatenate not + sign

if($fuel_type1 != 0) 
{ 
    $sql .= “ AND fuel_type IN ('$fuel_type1', '$fuel_type2', '$fuel_type3', '$fuel_type4')”;
}