tags:

views:

193

answers:

2

Hi,

When i try to send email from while loop with phpmailer, it sometimes sends 2, sometimes 3 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 = "[email protected]";
    $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 viewer!";

    $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 while loop and get all the emails from an array ?

or you think it is problem with 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 ! T

+1  A: 

Just put a "SELECT DISTINCT" on your query and you'll no longer see problems with your database.

Hisamu
thanks but i checked it, it is not about database dublicate, it is about loop, i need to reset $body variable i guess
Ahmet vardar
+1  A: 

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:

http://stackoverflow.com/questions/1610582/cleaning-post-variables/1610601#1610601

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.

Andi