1

I have a table, where I have fields like ID, username, address1, address2, zipcode, description etc. Well, I want to get all the rows as a result where 'ID' must not be equal to '$_SESSION['id']' and 'add1' must be equal to 'address1' or add2 must be equal to 'address2'.

My query is as follows :

$res = mysqli_query($con,"
SELECT * 
  FROM tabledata 
 WHERE ID !='$_SESSION['id']' 
   AND address1 = '$add1' 
    or address2 = '$add2' 
 ORDER 
    BY id DESC 
 LIMIT 5
");

But this query is giving me that row as well for which 'ID' value is equal to '$_SESSION['id']'.

Probably there would be any other way...but I could not figure it, any help or suggestion would be appreciated.

Strawberry
  • 33,750
  • 13
  • 40
  • 57
  • 5
    Looks like a [operator precedence](https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html) problem .. – Raymond Nijland Jan 18 '19 at 13:31
  • 5
    You need parenthesis around the OR, as in `AND (address1 = '$add1' or address2 = '$add2') ORDER BY`. A good SQL tutorial will help you understand these sorts of things. – Ken White Jan 18 '19 at 13:31
  • 1
    I also advice you to read [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) and if @KenWhite suggestion not works in advice you to read [Why should I provide an MCVE for what seems to me to be a very simple SQL query?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a-very-simple-sql-query) and provide example data.. – Raymond Nijland Jan 18 '19 at 13:33
  • Thank you for the help @ Raymond Nijland and @Ken White, I thank you both, Its fixed by using parenthesis, and surely I'll check the links you have provided. – Shivkesh Dwivedi Jan 18 '19 at 13:39

1 Answers1

1

Maybe Like This:

$res = mysqli_query($con,"
SELECT * 
  FROM tabledata 
 WHERE ID <> '$_SESSION['id']' 
   AND (
             address1 = '$add1'
          OR address2 = '$add2' 
   )  
 ORDER 
    BY id DESC 
 LIMIT 5
");
mscdeveloper
  • 2,749
  • 1
  • 10
  • 17