amadeo
amadeo

Reputation: 109

MySQL WHERE doesn't work properly

I have a category.php page which shows all the articles in a given category ($tagname) where enabled=1. When an article has only one tag (and two empty ones) then everything is fine. The article will be shown on this category.php page (when enabled is set to 1). However, if at least two tags are filled then the article will show up on the category.php page where tag2=$tagname or if tag3=$tagname - no matter what the enabled field contains (1 for enabled, 2 for disabled)!

Bottom line - why does it show up even though enabled is set to 2 for that article?

SELECT *
FROM articles
WHERE enabled=1
  AND tag1='$tagname'
  OR tag2='$tagname'
  OR tag3='$tagname'

enabled, int
tag1, varchar(30)
tag2, varchar(30)
tag3, varchar(30)

Thanks!

Upvotes: 0

Views: 60

Answers (4)

Ilesh Patel
Ilesh Patel

Reputation: 2155

Try This :

SELECT *
FROM articles
WHERE enabled=1
  AND (tag1='$tagname'
       OR tag2='$tagname'
       OR tag3='$tagname')

Upvotes: 1

Manibharathi
Manibharathi

Reputation: 945

Use this query.

SELECT *
FROM articles
WHERE enabled=1
  AND (tag1='$tagname'
       OR tag2='$tagname'
       OR tag3='$tagname')

Upvotes: 1

Rakesh Sharma
Rakesh Sharma

Reputation: 13738

try to separate your conditions

SELECT *
FROM articles
WHERE enabled=1
  AND (tag1='$tagname'
       OR tag2='$tagname'
       OR tag3='$tagname')

so now it will be check result where enabled=1 and any tag result ture from 3

Upvotes: 1

Ravinder Reddy
Ravinder Reddy

Reputation: 24002

AND has high precedence over OR and hence in your query

First enabled=1 and tag1='$tagname' is evaluated and then
its result is compared to next OR expression and so on...
Unless you separate AND conditions with OR conditions properly, out put would be as unexpected.

Change your query as below:

SELECT * FROM articles 
 WHERE enabled=1 
   AND (tag1='$tagname' OR tag2='$tagname' OR tag3='$tagname')

Refer to: Operator Precedence

Upvotes: 2

Related Questions