What I would like to know is:
1 - what is the best way to loop through the results I get from the db? In my first example I first build a multidimensional array and then split it using array_chunk(). I have a feeling that that is a bit laborious, compared to the second example.
2 - when should I implement a delay with sleep()? From what I know, using the phpmailer class I should be able to send quite a lot of emails before the script runs out of time. So, what are your guesses. Can I run the script for less then 1000 mails without a sleep() build in?
3- If needed, what is the best way to implement a delay? Assuming I try to do it in the script itself, and not use a cron job (which many would advice).
Version 1:
Code: Select all
<?php
set_time_limit(300); // 5 minutes
if(isset($_POST['submit']))
{
// validation of $_post values here....
// Setup body here ...
// instantiate the class here ...
// Get the user's Email
$sql = 'SELECT FirstName,LastName,EmailAddress,MailType FROM mymaillist_subscribers';
$result = $db->query($sql); // create MySQLResult object. I use a MySQL class from the php anthology books
$mails = array();
while ($rows = $result->fetch()) {
$mails[] = $rows;
}
$chunks = array_chunk($mails, 50);
foreach($chunks as $value)
{
foreach($value as $row)
{
// Send the emails in this loop.
$member_name = $row['FirstName'] .$row['LastName'];
$member_address = $row['emailaddress'];
$mailer->AddAddress($member_address);
$mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $htmlBody);
$mailer->IsHTML(true);
$mailer->AltBody = str_replace('{MEMBER_NAME}', $member_name, $textBody);
$mailer->Send();
$mailer->ClearAddresses();
$mailer->ClearAttachments();
$mailer->IsHTML(false);
echo "Mail sent to: $member_name<br />";
}
// Have the loop sleep a few secs
sleep(3);
}
}
?>Code: Select all
<?php
...
$x = 1;
$hold = 50;
while($row = $result->fetch())
{
// Send the emails in this loop.
$member_name = $row['name'];
$member_address = $row['emailaddress'];
$mailer->AddAddress($member_address);
$mailer->Body = str_replace('{MEMBER_NAME}', $member_name, $htmlBody);
$mailer->IsHTML(true);
$mailer->AltBody = str_replace('{MEMBER_NAME}', $member_name, $textBody);
$mailer->Send();
$mailer->ClearAddresses();
$mailer->ClearAttachments();
$mailer->IsHTML(false);
echo "Mail sent to: $member_name<br />";
// delay method:
$x++;
if($x == $hold)
{ // When $x is equal to $hold, a 3 sec delay will occur avoiding php to timeout
sleep(3);
$x = 0;
}
}
...
?>Thanks, Matthijs