0

I have this code for sending mails to users from DB, but mail is always sent just to first user, even if changing order. (request is sent from AJAX)

    $headers = ...

    $mailbody = ...

    $sql = 'SELECT `email`, `name` FROM `users`'; 
    $result = mysqli_query($link, $sql) or die(mysqli_error($link));

    while ($row = mysqli_fetch_array($result)) {
            $rows[] = $row;
            }

    foreach ($rows as $row) {
            if (mail($row['email'],"title", $mailbody, $headers)) {
            echo 'mail '.$row['name'].' OK';
            return TRUE;
          } else {
            echo 'MAIL ERROR!!!';
            return FALSE;
          }
    }
2
  • You're returning from the function after you send the first mail. Commented May 26, 2015 at 9:04
  • did you print_r($rows) Commented May 26, 2015 at 9:05

4 Answers 4

1

It's because you do return TRUE after the first successful mail. That ends the function. Take out that line, and put it after the foreach is done.

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

1 Comment

Thanks everyone for help! Worked!
0

return TRUE; and return FALSE; stop the foreach loop.

Comments

0

It's because of this line: return TRUE;. It's causing your function/script to end right there, instead of continuing with the foreach loop.

If you want the script to stop on the first failure, this should work:

$sql = 'SELECT `email`, `name` FROM `users`'; 
$result = mysqli_query($link, $sql) or die(mysqli_error($link));

while ($row = mysqli_fetch_array($result)) {
        $rows[] = $row;
        }
foreach ($rows as $row) {
        if (mail($row['email'],"title", $mailbody, $headers)) {
        echo 'mail '.$row['name'].' OK';
      } else {
        echo 'MAIL ERROR!!!';
        return FALSE;
      }
}
return TRUE;

It will return true if all the emails have been sent sucessfully, otherwise it will return false on the first failure.

Comments

0

Because you use return true or false the foreach loop stop remove it and try again or you can wrap it in a function and then if success return true (after the foreach loop) else return false

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.