1

I am trying to write some PHP code that emails every user in my database (around 500) their usernames. I have successfully managed to pull the email addresses and usernames for each user and store them in an array. However, I cannot figure out how to email each individual user with their individual usernames. I am pretty sure I need to use a foreach loop to do this, but I have had no luck. Here is what I have.

<?php
include('databaseConn.php');

$query = mysql_query("SELECT * FROM staff");
$emailArray;

while ($row = mysql_fetch_array($query)) {
$emailArray[] = array($row['email']=>$row['username']);
}

print_r($emailArray); //This associative array now contains each username along with their respective email address.

?>

==***********=== WITH MAIL FUNCTION

<?php
include('functions/core.php');

$query = mysql_query("SELECT * FROM users");
$emailArray;

while ($row = mysql_fetch_array($query)) {
    $emailArray[] = array($row['email']=>$row['username']);
}

foreach($emailArray as $email => $username) {
    echo $username; // outputs the indexes.


$subject = 'Accoutn Details';

$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$username.'</b><br/>
<br/><br/>Kind regards,<br/>';

$headers = 'From: noreply@xxxxx.co.uk' . "\r\n" .
    'Reply-To: noreply@xxxxx.co.uk' . "\r\n" .

$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 

mail($emailAddress, $subject, $message, $headers);

}


//print_r($emailArray);

?>
4

2 回答 2

0

如果您的问题是如何使用 foreach... http://www.php.net/manual/en/control-structures.foreach.php

例如:

foreach ($emailArray as $email => $username) {
    // Send an email to $email with their $username
}

@Dagon 是对的,如果您不需要关联数组,则无需迭代两次。即使您确实需要一个数组,它也不一定必须是关联的;它可能是数据库中的原始行,您可以对其进行迭代。唯一需要关联数组的时候是当您需要通过键(电子邮件地址)查找值(用户名)时,据我所知,您不需要这样做。

于 2013-03-19T21:41:44.123 回答
0

在循环中使用邮件是个坏主意,除非它是一次性的,听起来像这样,而且大多数共享主机不允许一次发送 500 封电子邮件。

$subject = 'Account Details';
$headers = 'From: noreply@xxxxx.co.uk' . "\r\n" .
    'Reply-To: noreply@xxxxx.co.uk' . "\r\n" .

$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; 

while ($row = mysql_fetch_array($query)) {

$message = 'This email contains your login details.<br/><br/>
<b>Username: '.$row['username'].'</b><br/>
<br/><br/>Kind regards,<br/>';

mail("$row['email']", $subject, $message, $headers);

    }
于 2013-03-19T21:47:52.320 回答