Search code examples
phpsqloperatorsforum

SQL Operators: AND and OR


I'm just wondering if you can use both of them in a PHP code. I thought something like this:

$sql2 = mysql_query("SELECT * FROM forum WHERE id='$topicsnumber' AND main='0' OR main='1' OR main='2'");   
while($row=mysql_fetch_array($sql2)) {code in here}

So that it checks it like this WHERE id='$topicsnumber' AND (main='0' OR main='1' OR main='2'). Is this possible?


Solution

  • Yes, it's possible with parentheses around the conditions, but it's better written as

    mysql_query("SELECT * FROM forum WHERE id='$topicsnumber' AND main IN ('0','1','2')");
    

    That way you don't have to worry about operator precedence.

    If main is a numeric data type, you can drop the apostrophes around the numbers in your query.