Sql请教许多WHERE LIKE字段

时间:2014-09-05 16:23:53

标签: php mysqli where sql-like

我为搜索者编程,此搜索者使用城市代码(或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"是我桌上的一块田地。

因此,在前端,用户可以在不同的"字段之间搜索"得到像名字,ocassion,zone,kindfood这样的结果。

在我的咨询中我有这样的事情:

$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。

1 个答案:

答案 0 :(得分:1)

括号是你的朋友:

$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

Read up on the concept of 'operator precedence'