Search query shows all records when searching in two columns and search word is empty

前端 未结 1 808
無奈伤痛
無奈伤痛 2021-01-27 06:21

I am having an issue with a query I am using.

There are two things to search for, a category and a searchword, category searches within a category column in my database,

相关标签:
1条回答
  • 2021-01-27 07:17

    Your problem is in operator precedence in your WHERE clause. At present, when $trefwoord is empty, your WHERE clause looks like this:

    WHERE cnt.title LIKE '%%' OR
          cnt.introtext LIKE '%%' AND 
          cat.alias LIKE 'something'
    

    This is evaluated as

    WHERE cnt.title LIKE '%%' OR
          (cnt.introtext LIKE '%%' AND cat.alias LIKE 'something')
    

    which will always be true (cnt.title LIKE '%%' will always match). You need to resolve this by using parentheses appropriately, so the WHERE clause looks like

    WHERE (cnt.title LIKE '%%' OR cnt.introtext LIKE '%%') AND 
          cat.alias LIKE 'something'
    

    So, in your PHP write:

    WHERE (cnt.title LIKE '%".$conn->real_escape_string($trefwoord)."%' OR
    cnt.introtext LIKE '%".$conn->real_escape_string($trefwoord)."%')
    ".$branchequery."
    
    0 讨论(0)
提交回复
热议问题