问题描述:

I am trying the following elseif statement to call the correct code based on a POST from the previous page and it has been defaulting to using only the first block of code i am aware that this might not be the best way to carry out the code in this situation so i'd like to ask if anyone has a more efficient way of doing this THANKS

elseif ($toyota="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";

}

elseif ($bmw="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";

}

elseif ($subaru="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";

}

elseif ($mitsubishi="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";

}

elseif ($nissan="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";

}

elseif ($mazda="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";

}

elseif ($chrysler="on"){

$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";

}

Forgot to mention,the post from html comes like

"toyota=on", "bmw=on" and so on

网友答案:
$cars = array('toyota', 'bmw', 'nissan');

foreach ($cars as $car) {
    if (!isset($_POST[$car]) || $_POST[$car] != 'on') {
         continue;
    }

    $query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
    break;
}
网友答案:

There is difference between = and ==.

= assigns value, whereas == compares value.

replace all your = with ==

($toyota=="on"){

There is much better way to do that instead of using so many if else blocks. try using a varibale in the query based on the input.

网友答案:

A single = will set a value whereas a double == will test for equality

elseif ($toyota=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}
相关阅读:
Top