dqwh1208 2014-03-15 01:11
浏览 45
已采纳

从PHP mySQL搜索结果中排除值

I have read up on excluding results in PHP and mySQL but I can't seem to figure out the correct syntax for the search code I am using.

In all of my other result tables that simply pull information from the database without having to use a search form, excluding userlevels has been easily achieved by simply including the following after the "WHERE" statement:

WHERE `userlevel` !='9' AND `userlevel` !='1' AND `userlevel` !='4' AND `userlevel` !='5' AND `userlevel` !='6'

Now, I'm using a search code that uses "OR" instead of "AND" and "LIKE" with the terms. It looks like this:

//Set the MySQL query
if ($search == NULL or $search == '%'){
} else {
for ($i=0; $i<count($keywords); $i++) {
$query = "SELECT * FROM sound_users " .
"WHERE genre LIKE '%".$keywords[$i]."%'".
" OR genre2 LIKE '%".$keywords[$i]."%'" .
" OR genre3 LIKE '%".$keywords[$i]."%'" .
" OR bandname LIKE '%".$keywords[$i]."%'" .
" ORDER BY genre";

}

I saw in some other forums that "NOT IN (SELECT *)...." is being used to exclude data but it seems like every code uses punctuation differently - has a different syntax - so I'm not so sure how to exclude specific values with this search code.

I have tried simple angles like:

" OR userlevel !='5'" .
" OR userlevel !='9'" .

and that only did funky things to the search results which wound up including both of those userlevels at the same time in two different tables stacked on top of eachother. So I changed the "OR" to "AND" - like it is in my other code and that didn't work either.

At that point, I tried to add the "NOT IN" and "NOT EXISTS" examples I found but any way I do it, always seems to come back with san error telling me to check the syntax.

I'm wondering if it's even possible to exclude specific values from search results using "OR" or if exclusion only works for basic code simply calling values from the database to display and not necessarily using a search form.

  • 写回答

1条回答 默认 最新

  • doucou1892 2014-03-15 01:16
    关注

    Parentheses are your friend!

    WHERE 
      (X LIKE '%X%' OR Y LIKE '%Y%' OR Z LIKE '%Z%')
      AND
      (X NOT LIKE '%XX%' OR Y<>'abc' OR LENGTH(Z)<5 OR A<>7)
    

    BTW: The usual notation for unequality in SQL is <>, not !=

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问