Reputation: 25
Need your help with my PHP/MYSQL array.
I have a php script that selects users from a string like this: [email protected], [email protected], [email protected]
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 protected], [email protected], [email protected]
$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.
Upvotes: 0
Views: 356
Reputation: 37645
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
Upvotes: 0
Reputation: 360572
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.
Upvotes: 0
Reputation: 9671
You can save the found emails in an array and do an array_diff()
with both:
$splitdata = array([email protected], [email protected], [email protected])
$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.
Upvotes: 2