简体   繁体   中英

PHP Array in MYSQL select

Need your help with my PHP/MYSQL array.

I have a php script that selects users from a string like this: email@email.com, email@email2.com, email@email3.com

I have a MYSQL database where some registrated users are present with their email adresses. The script needs to check if the email adress is present in the rows like this:

 $splitdata = for example: email@email.com, email@email2.com, email@email3.com

 $sql= mysql_query("SELECT * FROM `users` WHERE `email` IN ('".join("','", $splitdata)."')")     or die ('Error: '.mysql_error ());
Then i get the result with a MYSQL fetch array:

while($result = mysql_fetch_array($sql)) {      
    $email = $result['email'];
...

For the results i insert a value in another table. But only for the email adresses that could be found in de rows.

What i need:

I want to send an email to the email adresses of the users that were not found in the table. For an invite to the software. It now only works with users that could be found, but i need to do a different action to who couldn't be found.

It does not have to be in the same MYSQL fetch, i can create another mysql fetch for all the email adresses that could not be found in the database. I need some example code or somebody who know how to do this.

Currently have tried NOT IN but it gave me a result of every user in the list except the ones that could be found. The result must be the email adresses that could not be found.

You can save the found emails in an array and do an array_diff() with both:

$splitdata = array(email@email.com, email@email2.com, email@email3.com)
$sql= mysql_query("SELECT * FROM `users` WHERE `email` IN ('".join("','", $splitdata)."')")     or die ('Error: '.mysql_error ());
while($result = mysql_fetch_array($sql)) {      
    $emailsFound[] = $result['email'];
    $email = $result['email'];
}

$emailsNotInResults = array_diff($splitdata,$emailsFound);

This will give you an array of emails which were in your $splitdata but couldn't be found in the database.

Getting an error on the fetch call usually means your query failed, and you've gotten back a boolean FALSE instead of a statement handle.

Try checking for query failure first:

$sql = mysql_query("....");
if ($sql === FALSE) {
    die(mysql_error());
}

before doing the fetch call.

I could kludge up a single query for this, but I'd keep it simple and just query one email at a time.

SELECT CASE WHEN EXISTS (SELECT 1 FROM users WHERE email = '$email') THEN 'yes' ELSE 'no' END

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