I'd just like to check, is this a good way of iterating over rows in a database and deleting them when processed? I first had
- Grab all
- Process all
- Delete all
But figured that might leave to problems if new rows were added (from outside) while the "Process all" step is running.
// the limited for loop is to prevent an infinite loop
// assume the limit to be much higher than the expected
// number of rows to process
for ($i = 0; $i < $limit; $i++)
{
// get next mail in queue
$st = $db->prepare('
SELECT id, to, subject, message, attachment
FROM shop_mailqueue
LIMIT 0,1
');
$st->execute();
$mail = $st->fetch(PDO::FETCH_ASSOC);
// if no more mails in queue, stop
if ($mail === false) {
break;
}
// send queued mail
$mailer = new PHPMailer();
$mailer->AddAddress($mail['to']);
$mailer->SetFrom('[email protected]', 'xxx.nl');
$mailer->Subject = $mail['subject'];
$mailer->Body = $mail['message'];
$mailer->AddAttachment($mail['attachment']);
$mailer->Send();
// remove mail from queue
$st = $db->prepare('
DELETE FROM shop_mailqueue WHERE id = :id
');
$st->bindValue('id', $mail['id']);
$st->execute();
}