douan5151 2014-08-22 11:46
浏览 50

从mySQL查询中删除未找到的单词

I am trying to make search and need to remove word from query, that do not have match.

Lets say there is 3 words: one, two and three. If one is not found, then I need to rerun query with other two words (I get result Where empty_space AND two AND three, so query finds nothing). And so on. But I don't know how to identify unmatched word and run query again with other two words.

EDIT: If I use this code, to count elements in array with $i++, query - one two three:

if(!empty($d)) {
     if($i < 2) {
      $like_str .= " (title LIKE '%".$keyword."%')";
     } else {
      $like_str .= " AND (title LIKE '%".$keyword."%')";
     }
    }

Result: SELECT * FROM shop_products_ WHERE AND (title LIKE '%two%') AND (title LIKE '%three%')

And with words that exist, query - one two

if(!empty($d)) {
     if($key < 1) {
      $like_str .= " (title LIKE '%".$keyword."%')";
     } else {
      $like_str .= " AND (title LIKE '%".$keyword."%')";
     }
    }

Result: SELECT * FROM shop_products_ WHERE (title LIKE '%one%') AND (title LIKE '%two%')

  • 写回答

2条回答 默认 最新

  • duanpang1987 2014-08-22 11:49
    关注

    Simply don't AND the constraints but OR them. Any unmatched word will not interfere with the others, like this:

    WHERE w = 'one' OR w = 'two' OR w = 'three'
    

    If one does not exist, it will be identical to:

    WHERE w = 'two' OR w = 'three'
    

    Anyways, I'd recommend to NOT paste your SQL query out of strings in PHP, this is very much subject to SQL-injection and a totally abandoned and discouraged practice. What you should use are parameters, depending on the actual implementation (mysqli? PDO?) similar to this:

    WHERE w = ? OR w = ? OR w = ?
    

    On the other hand, if you need an arity of n, you may want to use the IN clause:

    WHERE w IN ('one', 'two', 'three')
    

    But here you can't use parameters because of technical constraints. More about it here: Binding parameters for WHERE IN clause with PDO

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看