When I try to send email from the while loop with PHPMailer, it sometimes sends 2, sometimes 3 copies of the same email (it is like random) to each recipient.
Here is my code. Do you think it has problems?
$list = $_POST['list'];
$items = rtrim($_POST['items'],",");
$query = "SELECT * FROM `mail` WHERE `ID` IN ($items)";
$result = mysql_query($query);
$from = "donotreply@mysite.net";
$fromname = "mysite";
$mail = new PHPMailer(true);
$mail->IsSendmail();
$mail->From = $from;
$mail->FromName = $fromname;
$mail->Subject = "Your subscription was confirmed";
while ($row = mysql_fetch_array ($result))
{
// HTML body
$body .= "<p>Hi ". $row['name'] ." <br /><br />";
$body .= "Your subscription request to " . $l_name ."'s list was confirmed.<br /><br />";
$body .= "Thank You !<br /><br />";
// Plain text body (for mail clients that cannot read HTML)
$text_body = "To view the message, please use an HTML compatible email v开发者_开发问答iewer!";
$mail->Body = $body;
$mail->AltBody = $text_body;
$mail->AddAddress($row['email']);
$mail->Send();
$mail->ClearAddresses();
}
Do you think should I put that mail->send();
out of the while loop and get all the emails from an array?
Or do you think it is the problem with the MySQL query?
Edit: I checked database, no problem about database but i figured out that (lets say there are 2 mail in the array) it sends first email normally but second one goes with dublicated $body variable, i mean it sends $body variable dublicated.
FIX: hey, I done, I just added $body = "";
and it works perfect now!
I think more than likely to be duplicate data in the database.
Also i'm concerned about the lack of validation (or non at all) on the POST array.
May be worth you looking at this:
cleaning $_POST variables
Update: While you can just use DISTINCT on the query i would question how the duplicates got there in the first place and look at that as a seperate issue.
Just put a "SELECT DISTINCT"
on your query and you'll no longer see problems with your database.
You mentioned the fix at the end of your question, but here's why that makes a difference:
The .=
operator appends to the existing value, whereas =
overwrites it. At the end of the first iteration and start of the second, $body
contains the email body, during the second iteration, you then append to the existing value. Each time the loop executes, you add another copy to the end of the email. As you said, setting $body = ""
fixes it because it empties the body of the email.
Another way to fix it would be to make the first assignment =
instead of .=
:
while ($row = mysql_fetch_array ($result))
{
// HTML body
$body = "<p>Hi ". $row['name'] ." <br /><br />"; // This line only has '='
$body .= "Your subscription request to " . $l_name ."'s list was confirmed.<br /><br />";
$body .= "Thank You !<br /><br />";
// etc...
}
精彩评论