ROY Finley
ROY Finley

Reputation: 1416

PHP / Mysql problems with the IN operator

All bounced emails are sent to a table in my database. I am trying to compare them to a field in another table that is populated with my active emails. Using the following function it returns nothing when using "IN" and all when using "NOT IN", but i know that there are matching emails in the two tables. am i going at this the wrong way?

<?php
function CompareEmails() {
    $mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
        echo $mysqli->connect_error;
        $mysqli->close();
    }

    $bademails = array();
    $values = $mysqli->query("SELECT bad_emails.emails FROM bad_emails ");

    while ($row = $values->fetch_assoc()) {
        $bademails[] = $row['emails'];
    }

    $query = "SELECT email_database.customer_id, email_database.email 
              FROM email_database 
              WHERE email_database.email IN('" . implode("' , '", $bademails) . "') 
              ORDER BY email_database.customer_id DESC";

    $values2 = $mysqli->query($query);

    while ($row2 = $values2->fetch_assoc()) {
        echo $row2['customer_id'] . " " . $row2['email'] . "</br>";                                                                                                            
    }                                                                                                                                                                          
}                                                                                                                                                                              
?>

Upvotes: 1

Views: 325

Answers (1)

Mike Brant
Mike Brant

Reputation: 71422

You could do this all much more nicely in a single query like this:

SELECT e.customer_id, e.email
FROM email_database AS e
INNER JOIN bad_emails AS b ON e.email = b.emails
ORDER BY e.customer_id DESC

Note that I used b.emails (plural) joined to e.email (singular) to match what you show in your queries. I am guessing that this might actually be the problem you are having in that you might be getting an empty result set if you are not referring to the field name correctly in bad_emails (is it really just email?). that would lead to the exact IN/NOT IN behavior you are seeing.

Just change my query to use whatever the correct name is.

Upvotes: 1

Related Questions