Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query with 2 OR statments and 1 AND statement

I am attempting to run a SQL query like this:

$sql = mysql_query("select * from users where new_mail = 0 OR new_events = 0 and emailed = 1") or die(mysql_error());
while($r=mysql_fetch_array($sql))
{
    mysql_query("update users set emailed = 0 where username='{$r['username']}'") or die(mysql_error());
}

However it seem to ignore the OR statements and only follows the and statement. So it goes ahead and sets emailed to 0 even if they still have new_mail or new_event. Any clue why?

Thanks for your help!

like image 449
alexander7567 Avatar asked Dec 21 '25 11:12

alexander7567


1 Answers

In MySQL, the AND operator has a higher precedence over the OR operator.

To get the logic you desire, try grouping the parameters in the way you want them to be evaluated:

$sql = mysql_query("select * from users where (new_mail = 0 OR new_events = 0) and emailed = 1") or die(mysql_error());
like image 168
newfurniturey Avatar answered Dec 23 '25 01:12

newfurniturey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!