循环数据库记录集

时间:2015-11-20 11:41:42

标签: php

我希望向一个地址发送电子邮件,并发送从表格中提取的其他地址。

// get all cc email id's for this users site
$results3h = mysql_query("SELECT user_id FROM company_ccemails WHERE site_id = '$site_id' ");
echo mysql_error();                 
while($row = mysql_fetch_array($results3h))
    { 
        $cc_id = $row['user_id'] ;

        //get email addresses for each id

       $results3i = mysql_query("SELECT username FROM user WHERE id = '$cc_id' ");
       echo mysql_error();      

       while($row = mysql_fetch_array($results3i))
           { 
              $ccemails = $row['username'] . "," ;
           }
           mysql_free_result($results3i); 
}   
mysql_free_result($results3h); 
//send emails to 

    $to = "support@mydomain.com ; ";
$subject = "$email_subject";
$message = "$email_message";                                        
$headers = "CC: " .$ccemails. "\r\n";
$headers .= "From: " . strip_tags($myusername) . "\r\n";
$headers .= "Reply-To: ". strip_tags($myusername) . "\r\n";
$headers .= "BCC: " .$myusername. "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";                                  
mail($to, $subject, $message, $headers); 

发送此电子邮件时,虽然有3个“cc”电子邮件地址,但仍会发送“至”和1个“cc”。如果我在$ ccemails = $ row ...下移动发送代码,那么将与support@mydomain.com一起分别向每个'cc'发送一封电子邮件。这导致支持@收到大量电子邮件。

如何更改代码以在一个字符串中获取cc电子邮件并作为一封电子邮件发送,以便支持只收到一份副本?

我对PHP编码(通常是ASP)相对较新,我确信这是直接的,但目前令我感到困惑

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

使用$ccemails = $row['username'] . "," ;,您将$row['username']的值分配给$ccemails变量。这意味着每次在循环中你覆盖它

您必须使用.=

concat字符串

请尝试以下方法:

$ccemails = ""; // define this here, because otherwise you will get a notice
while ( $row = mysql_fetch_array( $results3h ) ) {
    /**
     * Your code
     */
    while ( $row = mysql_fetch_array( $results3i ) ) {
        $ccemails .= $row['username'] . ",";
    }
    /**
     * Your code
     */
}