dongxie8856 2012-12-06 01:17
浏览 39
已采纳

IN运算符的PHP / Mysql问题

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>";                                                                                                            
    }                                                                                                                                                                          
}                                                                                                                                                                              
?>
  • 写回答

1条回答 默认 最新

  • duancaoqin6683 2012-12-06 01:24
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面
  • ¥15 itunes恢复数据最后一步发生错误
  • ¥15 关于#windows#的问题:2024年5月15日的win11更新后资源管理器没有地址栏了顶部的地址栏和文件搜索都消失了
  • ¥100 H5网页如何调用微信扫一扫功能?