PHP elseif语句默认为第一个块

时间:2016-01-22 13:50:26

标签: php mysql

我正在尝试以下elseif语句根据上一页的POST调用正确的代码,并且它一直默认只使用第一个代码块我知道这可能不是最好的方法来执行在这种情况下的代码,所以我想问一下是否有人有更有效的方式这样做谢谢

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%'";
}

忘了提,html的帖子就像 " toyota = on"," bmw = on"等等

3 个答案:

答案 0 :(得分:3)

$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;
}

答案 1 :(得分:1)

=和==之间存在差异。

=指定值,而==比较值。

将所有你的=替换​​为==

($toyota=="on"){

有更好的方法可以做到这一点,而不是使用那么多if else块。尝试根据输入在查询中使用varibale。

答案 2 :(得分:0)

单个=将设置一个值,而双==将测试相等性

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%'";
}