【问题标题】:Sql consult with many WHERE LIKE fieldsSql 咨询许多 WHERE LIKE 字段
【发布时间】:2014-09-05 16:23:52
【问题描述】:

我正在编写一个搜索器,此搜索器使用城市代码(或 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。

【问题讨论】:

  • 方括号、括号、括号
  • 谢谢。现在我可以睡觉了。问候。

标签: php mysqli where sql-like


【解决方案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'.

【讨论】:

  • 我觉得这很简单。我真的很感激你的帮助。现在我可以睡觉了。问候。
  • @Christian 然后您可以接受答案并将其标记为已解决,方法如下meta.stackexchange.com/a/5235
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2014-05-22
  • 1970-01-01
相关资源
最近更新 更多