I am working on rebuilding a newsletter system I wrote a while ago. The original system was based around using a flat file system, and I want to convert it over to MySQL. All I have left is to rebuild the end function. My problem is that I need to do is use a loop for every email stored in the database. I figured a each loop is the best way to do this, but how do you use MySQL and foreach together? Here’s my current code:
$run = mysql_query("SELECT email FROM newsletter");
foreach ($run as $value) {
mail($value, $subject, $_POST['message'], $headers);
}
I’ve tried a lot of different things and nothing seems to work. I’ve even tried something like this:
$run = mysql_query("SELECT email FROM newsletter");
$email = mysql_fetch_array($run, MYSQL_ASSOC)
$cols = implode (', ', $email);
$run2 = mysql_query("SELECT $cols FROM newsletter");
while($emaillist = mysql_fetch_array($run2, MYSQL_ASSOC)){
foreach ($emaillist as $value) {
mail($value, $subject, $_POST['message'], $headers);
}
}
That was based off of a few other examples i seem. it doesnt give any errors, but it doesnt send the email. I would greatly appreciate some help.
You have to fetch your results. You can’t use foreach, you’ll want to use while.
https://www.php.net/mysql_fetch_assoc