I got a problem with creating newsletter PHP file and implementing it.
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM news WHERE received='0' LIMIT 20");
$mail_body = "";
while($row = mysql_fetch_array($sql)){
$id = $row["ID"];
$name = $row["name"];
$email = $row["email"];
$mail_body= "Test message";
$subject = "PHP Newsletter";
$headers = "From: no-reply@pageaddress.com
";
$headers = "Content-type: text/html
"; //To musi byc zawarte jeśli nasz email będzie w formie HTML
$to = "$email";
$mail_result = mail($to, $subject, $mail_body, $headers) or die ("Error!");
if ($mail_result) {
mysql_query("UPDATE news SET received='1' WHERE email='$email' LIMIT 1");
} else {
echo ("Some freaking error :o!");
}
}
?>
I do have a connection to my datebase. I did put one email - mine into this datebase. And I set received as default to 0 in my table. So when the loop begins it should get the array from my datebase --> send the email --> set the received to '1' and stop --> get the other email from the table and do the same.
But the problem is, that when I do into this address http://.../blast_script.php the script keeps sending me emails all the time. I have to remove the table from my datebase to stop it.
How to prevent this inifinite loop to send just one message to each email in the datebase?
The way the above query is written you would get exactly 20 emails since you're limiting that first select to 20 results.
I see no reason you would fall into an infinite loop. What have you done to debug each statement 1 by 1?
You should check that:
mysql_query("UPDATE news SET received='1' WHERE email='$email' LIMIT 1");
is working by checking that received is 1 in the database.
If not then you know that the received isn't correctly updating causing and infinite loop.
If you wish to test this and do not want to get 20 emails change the below code:
$sql = mysql_query("SELECT * FROM news WHERE received='0' LIMIT 20");
to
$sql = mysql_query("SELECT * FROM news WHERE received='0' LIMIT 1");
Try adding before the fetch loop:
$run_count = 1;
then in the loop add:
echo "The loop has been run $run_count times";
$run_count++;
That will tell you if the fetch loop is being hit too many times or if the problem is elsewhere
Also check the value of $mail_result is what you expect in each loop