PHP切换案例中的多个AND,

问题描述 投票:0回答:3

我正在制作一个带有两类单选按钮的Web应用程序。这两个类别将在case语句中用于执行sql查询。 $ state$ condition中存储着php会话,例如$ state的“ allstate”和“ new”,而$ all中存储了“ allcondition”和“ Available / Unassigned” 。实际上,每个都有两个以上。

我如何缩短case语句?我已经尝试制作带有多个OR的case语句,但是输出不是应该的。我也尝试使用if elseif。

<?php

switch($state AND $condition){
    case $state=="allstate" AND $condition=="allcondition":
        $sql3="SELECT *FROM eq_inv WHERE eq_condition='Available/Unassigned'";
        break;

    case $state=="new" AND $condition=="allcondition":
        $sql3="SELECT *FROM eq_inv WHERE eq_condition='Available/Unassigned' AND eq_state='new'";
        break;

    case $state=="old" AND $condition=="allcondition":
        $sql3="SELECT *FROM eq_inv WHERE eq_condition='Available/Unassigned' AND eq_state='old'";
        break;

    case $state=="Unknown state" AND $condition=="allcondition":
        $sql3="SELECT *FROM eq_inv WHERE eq_condition='Available/Unassigned' AND eq_state='Unknown state'";
        break;

    case $state=="Unknown state" AND $condition=="Available/Unassigned":
        $sql3="SELECT *FROM eq_inv WHERE eq_condition='Available/Unassigned' AND eq_state='Unknown state'";
        break;
}
//I did not put the rest of the code because it has 32 case statements
$result3=mysqli_query($conn,$sql3);
$count=mysqli_num_rows($result3);
echo "<label style='color:red;'><strong>".$count."</strong></label>";

?>

类别:

状态:所有状态,新的,旧的,未知状态

条件:所有条件,可用/未分配,修理,缺少零件,缺少eq,有缺陷,翻新,未知条件

php switch-statement
3个回答
0
投票

[switch($state AND $condition)将根据值$state$condition取值为真或假。

因此,唯一有用的情况是

  • case true
  • case false
  • case default

在您的情况下,您应该使用if / else构造。


0
投票

这呢?您甚至都不应该使用开关/外壳

<?php

$sql3 = "SELECT *FROM eq_inv WHERE eq_condition='".$condition."' AND eq_state='".$state."'";
$result3 = mysqli_query($conn, $sql3);
$count = mysqli_num_rows($result3);
echo "<label style='color:red;'><strong>".$count."</strong></label>";

注意:您当然应该添加转义字符以防止SQL注入,并可能考虑切换到PDO。


0
投票

您可以尝试以下方法:

<?php
$sql3="SELECT *FROM eq_inv WHERE eq_condition='Available/Unassigned'";

if(in_array($state, ['new', 'old', 'Unknown state']) && in_array($condition, ['allcondition', 'Available/Unassigned'])) {
  $sql3 .=" AND eq_state='".$state."'";
}

$result3=mysqli_query($conn,$sql3);
$count=mysqli_num_rows($result3);
echo "<label style='color:red;'><strong>".$count."</strong></label>";
?>
© www.soinside.com 2019 - 2024. All rights reserved.