Denoteone
Denoteone

Reputation: 4055

MySQL OR in query

Can I use "OR" in a mysql statement to check a fields value against multiple options?

    //THE QUESTION IF HAVE IS HOW DO I DO SOMETHING LIKE BELOW  MAINLY THE "1 OR 2 OR 3 OR 4" PART.

    $sql = "SELECT email FROM USER_INFO WHERE storeID = '$storeNUM' AND region = '1 OR 2 OR 3 OR 4'";
   $results2 = $db->query($sql);

Upvotes: 2

Views: 74

Answers (5)

nickb
nickb

Reputation: 59699

You can use an array and implode it for a nice solution:

$regions = array( 1, 2, 3, 4);
$sql = 'SELECT email FROM USER_INFO WHERE storeID = "$storeNUM" AND ( region = ' . implode( ' OR region = ', $regions) . ' )';
echo $sql;

Output:

SELECT email FROM USER_INFO WHERE storeID = "$storeNUM" AND ( region = 1 OR region = 2 OR region = 3 OR region = 4 )

Demo

Upvotes: 0

Marc B
Marc B

Reputation: 360662

This is how you do such a match:

... AND region IN (1,2,2,4)

Upvotes: 4

Joe Stefanelli
Joe Stefanelli

Reputation: 135808

You can use IN as a shorthand for multiple OR tests.

SELECT email
    FROM USER_INFO
    WHERE storeID = '$storeNUM'
        AND region IN (1,2,3,4);

Upvotes: 8

abcde123483
abcde123483

Reputation: 3905

If region is a string, which you have it down to be, but it really has no reason to be:

$sql = "SELECT email FROM USER_INFO WHERE storeID = '$storeNUM' AND region REGEXP '1|2|3|4'";
$results2 = $db->query($sql);

Upvotes: -1

BudwiseЯ
BudwiseЯ

Reputation: 1826

You can use this:

$sql = "SELECT email FROM USER_INFO WHERE storeID = '$storeNUM' AND (region = 1 OR region = 2 OR region = 3 OR region = 4)";

Upvotes: 0

Related Questions