按多个字段搜索SELECT IN(所有内容)

时间:2019-11-28 21:28:03

标签: php mysql sql

我想搜索一些产品并获得结果。 这是我的PHP代码:

function Item_Search($AppID, $Keyword = '', $Wears)
{
    // expected $Wears = [1,0,1,0,1] , numbers can be diffrent from 0 to 1

    $WearNames = ['red', 'green', 'blue', 'yellow', 'black'];
    $FinalWear = [];

    foreach ($Wears as $i => $Wear) {
        if ($Wear == 1) {
            $FinalWear[] = $WearNames[$i];
        }
    }
    $FinalWear = json_encode($FinalWear);
    $FinalWear = str_replace(str_split('[]'), '', $FinalWear);

$ItemList = Query("SELECT * FROM items WHERE appid=$AppID 
AND name LIKE '%$Keyword%'
AND wear IN ($FinalWear)
");
}

此代码可以正常工作,但是有些产品没有任何颜色。在这种情况下,我想说一下是否所有颜色均为1(真),然后显示也没有颜色的产品。

所以我的问题是,我可以在$FinalWear中放入wear IN ($FinalWear)这样的东西,以便获得所有结果吗?

1 个答案:

答案 0 :(得分:1)

您可以取$Wear中元素的总和,如果与计数相同,则将设置所有元素。然后,您可以使用它向OR测试中添加wear条件,在设置wear中的所有元素后检查$Wear中的空字符串:

function Item_Search($AppID, $Keyword = '', $Wears)
{
    // expected $Wears = [1,0,1,0,1] , numbers can be different from 0 to 1

    $WearNames = ['red', 'green', 'blue', 'yellow', 'black'];
    $FinalWear = [];

    foreach ($Wears as $i => $Wear) {
        if ($Wear == 1) {
            $FinalWear[] = $WearNames[$i];
        }
    }
    $FinalWear = "'" . implode("','", $FinalWear) . "'";
    $EmptyWear = array_sum($Wears) == count($Wears) ? "OR wear = ''" : '';

    $ItemList = Query(<<<EOD
SELECT * 
FROM items 
WHERE appid=$AppID 
  AND name LIKE '%$Keyword%'
  AND (wear IN ($FinalWear) $EmptyWear)
EOD
);
}

3v4l.org上的(查询输出的)演示

请注意,如果$AppID$Keyword来自外部资源,则您的查询容易受到SQL注入的攻击,因此应使用准备好的语句来避免这种可能性。参见此question

如果wear为空意味着实际上是NULL,请将生成$EmptyWear的行更改为

 $EmptyWear = array_sum($Wears) == count($Wears) ? "OR wear IS NULL" : '';