phploopsconcatenation

Concatenate email recipients with commas in a loop


I am trying to send an email to all users from database with the value from textarea. But I am doing something wrong here. I think the problem is somewhere with selecting the data from database, because if I add just one email address manually it works.

PHP file

connection...

$banner = ($_POST['baner_text']);
$banner_message = str_replace("\n.", "\n..", $banner );

$sql_clients = "SELECT email FROM clients";
$result_clients = $conn->query($sql_clients);
        
while ($row = mysql_fetch_array($result_clients)) {
    $emails = $row['email'] . ",";
}

$to      = $emails;
$subject = '';

mail($emails, $subject, $banner_message);

Solution

  • You're not including extra emails in this part

    $result_clients = $conn->query($sql_clients);
    
            while($row = mysql_fetch_array($result_clients)){
                $emails = $row['email'] . ",";
            }
    

    The value is being overwritten. Instead of $emails = ..., use $emails .= ...

    .= adds extra text to the string, while = overwrites it.