简体   繁体   中英

Where IN multiple column in mysql from php array

Can't find how to do this query if clouse IN more than one column I have example:

$post = json_decode($HTTP_RAW_POST_DATA);
$phoneNumbers = implode(",", $post->phones);
$emails = implode(",", $post->emails);

$sql = "SELECT phone_number,email,id FROM users WHERE phone_number,email IN (($phoneNumbers),($emails))";
$result = mysql_query($sql);

Paramenters gets from post response, and I need to compare this with logical OR. This example don't worked for me, result is nothing. How I can do that. Thx

Join two WHERE IN with AND :

SELECT phone_number, email, id FROM users WHERE phone_number IN ({$phoneNumbers}) AND email IN ($emails)

If you need to match phone number AND email, than generate your query:

$ors = [];

foreach ($phoneNumbers as $i => $number) {
    $ors[] = "(phone_number = :phoneNumber{$i} AND email = :email{$i})";
    $params[":phoneNumber{$i}"] = $number;
    $params[":email{$i}"] = $emails[$i];
}

$query = $pdo->prepare("SELECT phone_number, email, id FROM users WHERE ".implode(' OR ', $ors));
$query->execute($params);
SELECT 
  phone_number,
  email,
  id 
FROM users 
WHERE phone_number IN ($phoneNumbers)
  OR email IN ($emails)
$post = json_decode($HTTP_RAW_POST_DATA);
$phoneNumbers = $post->phones;
$emails = $post->emails;

$ors = [];
foreach ($phoneNumbers as $i => $number) {
    $ors[] = "(phone_number = :phoneNumber{$i})";
    $params[":phoneNumber{$i}"] = $number;
}

foreach ($emails as $i => $email) {
    $ors[] = "(email = :email{$i})";
    $params[":email{$i}"] = $email;
}

$query = $pdo->prepare("SELECT phone_number, email, id FROM users WHERE ".implode(' OR ', $ors));
print_r($query);
$query->execute($params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM