0

I'm new in MySQL and trying to filter users base on age, gender, and chat_id,

with below query:

SELECT * FROM Users WHERE
age = 17
AND gender='$gender1' OR gender='$gender2'
AND chat_id <> '$chat_id'
LIMIT 1

when $age is 17, i get unexpected result and $age is not considered.

What am I missing?

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
Saadat
  • 163
  • 4
  • 15
  • 1
    What does "age = 17 doesn't working" mean? You get an error? unexpected results? What? – HoneyBadger Jan 10 '17 at 16:58
  • 4
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jan 10 '17 at 16:59
  • i get unexpected result and age is not considered in final result – Saadat Jan 10 '17 at 17:01
  • You probably need parentheses. – Dan Bracuk Jan 10 '17 at 17:01
  • 2
    This is a question about logical evaluation. You _probably_ need some brackets around `(gender='$gender1' OR gender='$gender2')`... – arkascha Jan 10 '17 at 17:02
  • where the code need parentheses? – Saadat Jan 10 '17 at 17:03
  • Thank you. I added brackets and its worked. – Saadat Jan 10 '17 at 17:10

1 Answers1

1

Change this:

AND gender='$gender1' OR gender='$gender2'

to this:

AND (gender='$gender1' OR gender='$gender2')

You can additionally read about operators here.

Arsen Khachaturyan
  • 7,904
  • 4
  • 42
  • 42
Dan Bracuk
  • 20,699
  • 4
  • 26
  • 43