循环数据库记录集创建的电子邮件

I wish to send an email to one address and cc to other addresses drawn from a table.

// 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. "
";
$headers .= "From: " . strip_tags($myusername) . "
";
$headers .= "Reply-To: ". strip_tags($myusername) . "
";
$headers .= "BCC: " .$myusername. "
";
$headers .= "MIME-Version: 1.0
";
$headers .= "Content-Type: text/html; charset=ISO-8859-1
";                                  
mail($to, $subject, $message, $headers); 

when sending this email only the 'to' and 1 'cc' is sent although there are 3 'cc' email address. if I move the send code under $ccemails = $row... then an email is sent to each 'cc' separately along with support@mydomain.com. this results in support@ getting lots of emails.

how do I change the code to get the cc emails in one string and send as one email so support only receives one copy?

I'm relatively new to PHP coding (usually ASP) and am sure this is straight forward but is confusing me at the moment

thanks for any help

With $ccemails = $row['username'] . "," ; you are assigning the value of $row['username'] to your $ccemails variable. This means you override it everytime in the loop.

You have to concat the string with .=

Try this below:

$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
     */
}