防止在FOREACH循环/语句中重复

时间:2015-11-10 12:20:22

标签: php sql

我正在使用此代码向我的相关合作伙伴发送电子邮件,我遇到的问题是,有时合作伙伴ID出现两次并向合作伙伴发送2封电子邮件(重复),我该如何防止这种情况?

$get_partner_id = "SELECT partner_id FROM partners_locations WHERE location_id ='$location_id'";

if ($partner_ids = $connect->query($get_partner_id)) {
  foreach ($partner_ids as $partner_id) {
    $partner_id = $partner_id['partner_id'];

    //CONVERT PARTNER IDS TO RELATED PARTNER NAME AND SEND
    $get_partner_names = "SELECT partner_name FROM partners WHERE partner_id ='$partner_id' AND active ='yes'";

    if ($partner_names = $connect->query($get_partner_names)) {
        foreach ($partner_names as $partner_name) {
        $partner_name = $partner_name['partner_name'];

        // GET ADMIN EMAIL TEMPLATE
        ob_start();
        include (TEMPLATEPATH . '/quote/admin-email-template.php'); 
        $admin_message = ob_get_clean();

        @mail("alerts@myremovalsquote.com", "Referral for " . $partner_name . "", $admin_message, $admin_headers);
      }
    } 
    else {

    }                                                           
  }
} 
else {

}

1 个答案:

答案 0 :(得分:3)

首先,简化代码以使用单个查询。通常,在使用SQL时,您不需要在应用程序代码中使用循环。使用SELECT p.partner_name FROM partners_locations pl JOIN partners p ON p..partner_id = p.partner_id AND p.active ='yes'" WHERE pl.location_id = '$location_id';

SELECT DISTINCT

接下来,您可能遇到数据问题,其中合作伙伴在数据中多次列出,不知何故。如果这些值应该是唯一的,您可能需要调查一下。在此期间,您可以使用SELECT DISTINCT p.partner_name FROM partners_locations pl JOIN partners p ON p..partner_id = p.partner_id AND p.active ='yes'" WHERE pl.location_id = '$location_id';

echo "export DEVENVHOME=${DEVENVHOME:-$workarea/devenv.x}" >> .bashrc