简体   繁体   中英

How to send email to emails generated in while loop with specific row information?

I am pulling email addresses from a database whose FEE1 (owed) is less than their SESSION1 (paid) ie they owe. I then want to subtract the two to get a figure for how much they owe and email this information to them.

My problem is everyone who owes is receiving everyone else's email ie EMAIL1 receives EMAIL1 and EMAIL2's information.

I am convinced the problem is my IF() statement. I have searched and found that I may need to use a FOREACH() statement but I have used it incorrectly and had the information repeated multiple times per email sent. PLEASE HELP a novice my code goes something like this...

while ($row = mysql_fetch_array($select)){ /*start while loop*/
    $amount = $row['fee1'] - $row['session1'];
    $name = $row['name'];
    $surname = $row['surname'];
    $pname = $row['parentsname'];
    $psname = $row['parentname'];

    if ($row['session1'] < $row['fee1']){ /*start if owe*/
        $to      = $row['email'];
        $subject = 'Payment Reminder TEST!!!';
        $message = "Hello $pname $psname, \n\nAmount Owed For Session 1: £ $amount\nChilds Name: $name $surname\n\n".$message;
        $headers = 'From: creditcontrol@s.org.uk' . "\r\n" .
        'X-Mailer: PHP/' . phpversion();

        mail($to, $subject, $message, $headers);
    } /*end if owe*/
} /*end while loop*/

Look at this line:

$message = "Hello $pname $psname, \n\nAmount Owed For Session 1: £ $amount\nChilds Name: $name $surname\n\n".$message;

Spot the mistake?

Clue: your adding the $message to the existing $message - look at the end of the line.

So your loop runs and you set $message to equal "Hello..." then on the next run through the loop you set the $message to equal "Hello..." and the previous contents of $message so now there's two messages in $message , and this will go on and on for every iteration.

Simply remove . $message . $message from the end.

Unrelated to your problem but you could also optimize your loop by adding the needed condition in your SELECT statement so that "if ($row['session1'] < $row['fee1']){ / start if owe /" is part of the SELECT and not your loop. That way you won't have to iterate over your complete data set, and the IF becomes redundant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM