PHP中的Foreach循环只获取第一个实例

时间:2014-03-05 16:14:15

标签: php mysql sql

我有以下代码用于向用户发送电子邮件提醒,但它只向列表中的第一个用户发送电子邮件,而其余用户不会通过电子邮件发送。该查询在SQL中工作以提取所有用户

$users = array(mysql_fetch_array(mysql_query("SELECT DISTINCT wp_users.* FROM wp_users LEFT JOIN (SELECT lead_id, MAX(case when field_number = 7 then value end) AS email, MAX(case when field_number = 8 then value end) AS tournament_id FROM wp_rg_lead_detail GROUP BY lead_id) AS t1 ON t1.email = wp_users.user_email AND t1.tournament_id = '$tournament_id' WHERE t1.lead_id IS NULL AND id !=1")));


// Create the replacements array
$replacements = array();
foreach ($users as $user) {
$replacements[$user['user_email']] = array (
'{user_login}' => $user['user_login']
);
echo $user['user_email'] . "<br />" . $user['user_login']; 
}

// Create the mail transport configuration
$transport = Swift_MailTransport::newInstance();

// Create an instance of the plugin and register it
$plugin = new Swift_Plugins_DecoratorPlugin($replacements);
$mailer = Swift_Mailer::newInstance($transport);
$mailer->registerPlugin($plugin);

// Create the message
$message = Swift_Message::newInstance();
$message->setSubject("Pure Fantasy Golf Pick Reminder for {user_login}");
$message->setBody("{user_login}, this is a reminder that you need to submit a pick for this weeks tournament " . $tournament_name . ". Please go to http://dev.purefantasygolf.com to make your pick now.");
$message->setFrom("purefantasygolf@gmail.com", "Pure Fantasy Golf");

// Send the email
foreach($users as $user) {
$message->setTo($user["user_email"], $user["user_login"]);
$mailer->send($message);
}

3 个答案:

答案 0 :(得分:2)

mysql_fetch_array无法获取包含所有行的数组。它在数组中一次一行地获取一行,并且数组元素中每列都有值。

答案 1 :(得分:1)

查看mysql_fetch_array的文档。

你需要像这样循环你的结果:

$result = mysql_query("SELECT DISTINCT wp_users.* FROM wp_users LEFT JOIN (SELECT lead_id, MAX(case when field_number = 7 then value end) AS email, MAX(case when field_number = 8 then value end) AS tournament_id FROM wp_rg_lead_detail GROUP BY lead_id) AS t1 ON t1.email = wp_users.user_email AND t1.tournament_id = '$tournament_id' WHERE t1.lead_id IS NULL AND id !=1");

$replacements = array();
while($user = mysql_fetch_array($result)) {
    $replacements[$user['user_email']] = array (
        '{user_login}' => $user['user_login']
    );
    echo $user['user_email'] . "<br />" . $user['user_login'];
}

答案 2 :(得分:0)

我不认为循环发送N封电子邮件是个好主意。这可能会导致性能问题(如果邮件列表中有超过10个用户)。我认为这里更好的解决方案是将所有用户添加为BCC并仅发送一封电子邮件。