I am trying to send an email to selected users from my database. I do a select query and then use the results of email addresses to send mail the them.
Code:
foreach($stmt->fetchAll() as $result)
{
$mail = $result['email'];
//Email information
$to_email = "$mail";
$from_email = "myemail@mysite.com";
$subject = "Subject";
$comment = "Content"
mail($to_email, "$subject", $comment, "From: Website <" . $from_email . ">");
}
It works, but send multiple emails to each user. For eg. If there are 10 users selected, each user receives 10 emails. I know that is because the foreach
, I have also tried with while
. But I do not know how to fix.
That is not how fetchAll() works. It gets you a result-array with all lines from your query. So if you use foreach($stmt->fetchAll() as $result)
you will loop multiple times over all your results. You need to fetch all results and then loop over them.
$results = $stmt > fetchAll ();
foreach (results as $result) {
...
}
Or use fetch() in your loop.
while (($result = $stmt -> fetch ()) !== false) {
...
}
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.