当前位置: 动力学知识库 > 问答 > 编程问答 >

php - mysql where like and statment isnt working

问题描述:

I have a search bar on my website and building a page to show parts that have LIKE description and LIKE part name from the keywords in the search.

is_sold will always be an int of 1 or 0.

part_status will always be 1 when approved to be shown on the homepage, search, or category list.

Here is my sql statement

$result = mysql_query("

SELECT *

FROM part

WHERE part_name LIKE '%" . $get_search . "%'

OR part_desc LIKE '%" . $get_search ."%'

AND is_sold = 0

AND part_status = 1

ORDER BY id DESC

")

It is listing the parts no matter if they are approved and no matter if they are sold or not.

The issue im having is the AND at the end that I set int numbers for 'is_sold' (is part is sold and 'part_status' (if part is approved by administrator).

网友答案:

You're mixing and and or without any (), which means MySQL is going to apply its internal operator precedence rules: http://dev.mysql.com/doc/refman/5.0/en/operator-precedence.html

You probably want:

((part_name LIKE x) OR (part_desc LIKE X)) AND (is_sold = 0) AND (part_status = 1)

Note the extra brackets around the or components.

网友答案:

The problem is your combination of OR and AND:

WHERE part_name LIKE '%" . $get_search . "%'
  OR part_desc LIKE '%" . $get_search ."%'
  AND is_sold = 0
  AND part_status = 1

Now when the second condition is matched - the OR condition - the whole statement evaluates to true.

You need something like:

WHERE (part_name LIKE '%" . $get_search . "%'
       OR part_desc LIKE '%" . $get_search ."%')
  AND is_sold = 0
  AND part_status = 1
网友答案:

You have to structure your condition by parenthesis (), like this

$result = mysql_query("
SELECT *
FROM part
WHERE (part_name LIKE ('%" . $get_search . "%')
  OR part_desc LIKE ('%" . $get_search ."%'))
  AND is_sold = 0
  AND part_status = 1
ORDER BY id DESC
");
网友答案:

While I agree with esqew (you really should not use mysql_query), try this:

$result = mysql_query("
SELECT *
FROM part
WHERE (part_name LIKE '%" . $get_search . "%'
  OR part_desc LIKE '%" . $get_search ."%')
  AND is_sold = 0
  AND part_status = 1
ORDER BY id DESC
")
分享给朋友:
您可能感兴趣的文章:
随机阅读: