Question

Hung up on getting Swift “setTo” to accept an array from MySQL query. The code below only sends to the LAST person in the result set / list. Have read at least a dozen related threads on stack and the docs from Swift but they seem to only show how to hard code values OR make a lot of assumptions. Hoping for a more complete example that might also help others who aren't 100% on Php arrays and passing to Swift.

[...php connection code...]
// query email addresses
$sql = 'select emailaddress from customerlist;';
$result = mysql_query($sql );
if($result === FALSE) { 
    die(mysql_error()); // ToDo: better error handling 
} 

// create array from results
$cDistribArray = array();
while($rowEmail = mysql_fetch_assoc($result)) {
    $cDistribArray = $rowEmail['emailaddress'];
}

[edit: issue was code above, CORRECTED below, thanks Sven]
// create array from results
$cDistribArray = array();
while($rowEmail = mysql_fetch_assoc($result)) {
    $cDistribArray[] = $rowEmail['emailaddress'];
}


[...skip to Swift message create code...]

$message = Swift_Message::newInstance('Subject')
    ->setFrom(array('sender@yourserver.com' => 'Sender Name'))
    ->setTo($cDistribArray)
    ->setBody($cEmailBody,'text/html');

I'm sure it's something obvious I'm doing wrong with the array but after reading many articles on how to create arrays and Swift and an inbox full of test messages that only have more than one address when I hard code...stuck! Would appreciate any assistance offered.

Was it helpful?

Solution

This overwrites every previous result with the current fetched mail address:

$cDistribArray = $rowEmail['emailaddress'];

You probably want something like this:

$cDistribArray[] = $rowEmail['emailaddress']; // Add new mail address to the array

OTHER TIPS

The code that's sending the email is outside of the while loop. It'll only ever send an email to the last record. Have you tried this?

// create array from results
$cDistribArray = array();
while($rowEmail = mysql_fetch_assoc($result)) {
    $cDistribArray = $rowEmail['emailaddress'];

    [...skip to Swift message create code...]

    $message = Swift_Message::newInstance('Subject')
        ->setFrom(array('sender@yourserver.com' => 'Sender Name'))
        ->setTo($cDistribArray)
        ->setBody($cEmailBody,'text/html');

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top