0

I'm currently attempting to pull information from a database which is used to populate an email function. I'm trying to get it to send a number of emails equal to the number of email addresses stored in the database. (One row can have multiple email addresses stored in the same column, delimited by a comma).

(Example - [email protected], [email protected])

if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {

    if (strpos($row["mailcontacts"], ',') !== false) {
    $contact = explode(',', $row["mailcontacts"]);
        //print_r($contact);

    foreach ($contact as &$toaddress) {
        $mail->addAddress($toaddress);
    }} 

The functionality I want works for the first row that matches. It sends one email for the first row to dave and bob. However, any further rows the email gets sent to the contacts which it's already been sent to. Essentially Dave and Bob will be included on every email.

I've tried to unset each of the different variables in different places but I think this isn't where the issue is. If I use print_r($toaddress) as commented out it provides arrays for each row as needed.

2
  • 1
    You are always adding emails, newer resetting it's list. Commented Sep 29, 2017 at 11:11
  • If you are sending the same mail to all addresses, then make sure you don't send the mail within the while loop. Wait till the loop ends and all addresses are added, then send the mail after the loop. Commented Sep 29, 2017 at 11:20

1 Answer 1

1

If you're trying to send separate emails, you need to reset the addresses each time.

For example, something like:

<?php

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {

        $contacts = explode(',', $row["mailcontacts"]);

        foreach ($contacts as $toaddress) {
            $mail->addAddress($toaddress);
        }

        $mail->send();
        $mail->resetAddresses();
    }
} 

If your mailer class has no method to reset addresses, you'd probably have to create a new $mail each time round the loop.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.