Sql查阅了许多WHERE LIKE字段


Sql consult with many WHERE LIKE fields

我正在编程一个搜索器,该搜索器使用城市代码(或id_city)的条件,这意味着结果必须仅来自所选的一个或多个城市代码。因此,我为城市id_city=1和id_city=2传递值1,为城市id_city=3和id_city=4传递值2。

if ($city==1){
$setzone = "citycode in ('1','2')"; }
elseif($city==2){
$setzone = "citycode in ('3','4')";}

变量$setzone有我在sql中使用的数字,其中"citycode"是我表上的一个字段。

因此,在前端,用户可以在不同的"字段"之间搜索,以获得名称、位置、区域、食品等结果。

在我的咨询中,我有这样的东西:

$restaurants=$mysqli->query("select id, name,zone, ocassion, citycode, 
                                    kf.kindfood as food from restaurants as r
                                    inner join kind_food as kf on r.foodcode=kf.id_food
                                    where ".$setzone."
                                     and name like '%".$mysqli->real_escape_string($search)."%'
                                     or zone like '%".$mysqli->real_escape_string($search)."%'
                                     or ocassion like '%".$mysqli->real_escape_string($seach)."%'
                                     or kindfood like '%".$mysqli->real_escape_string($search)."%'
                                     order by id desc");

问题是,这个咨询只能搜索$setzone中的名称,但如果我搜索其他东西,比如kindfood、ocassion,zone会得到所有结果,并忽略$setzone。

括号是你的朋友:

$restaurants=$mysqli->query("select id, name,zone, ocassion, citycode, 
                             kf.kindfood as food from restaurants as r
                             inner join kind_food as kf on r.foodcode=kf.id_food
                             where ".$setzone."
here -->                     and (name like '%".$mysqli->real_escape_string($search)."%'
                             or zone like '%".$mysqli->real_escape_string($search)."%'
                             or ocassion like '%".$mysqli->real_escape_string($seach)."%'
                             or kindfood like '%".$mysqli->real_escape_string($search)."%'
and here -->                 ) order by id desc");

如果没有这两个括号,OR滤波器总是获胜。使用,可以将它们聚集在一起,但仍然需要$setzone

阅读"运算符优先级"的概念。