I am trying to email unique messages to individuals using information from a MySQL database. The emails are sent when a date is within 30 days.
Essentially the email recipient will get a user id, date, and some other values from the database that are specific to them when a date is reached.
I am having trouble figuring out how to send an email to recipient1 with their information, then an email to recipient2 with their information, recipient3 with their information, and so on, all within the same script.
I have gotten around this by setting a value within the database to look up whether or not an email was already sent and selecting LIMIT 1. If no email was sent the first record is selected and an email is sent. Upon completion the value is updated in the database so that record is skipped the next time.
I run this script using a CRON job on the server and it is working for one email at a time. It runs hourly, which I could tighten up but would prefer a single script to batch run for everyone once daily.
Does anyone know how I can accomplish sending separate emails to multiple recipients with recipient specific information from the database within a single script?
Here is my code:
===========================================================
<?php
require_once("dbconn.php");
if (!mysql_connect($DB_HOST, $DB_USER, $DB_PASSWORD))
die("Can't connect to database");
if (!mysql_select_db($DB_DATABASE))
die("Can't select database");
?>
<?php
$result = mysql_query("SELECT * FROM tablexyz WHERE field_target BETWEEN CURDATE() - INTERVAL 30 DAY AND CURDATE() AND field_status <> 'Complete' AND email_sent = 0 LIMIT 1");
if (!result) {
die("No data");
}
while ($row = mysql_fetch_array($result))
{
$from = "Name <email@domain.com>";
$header = "From: ".$from."rn";
$header .= "Reply-To: ".$from."rn";
$to = $row['email_to'];
$subject .= "Value ".$row['field_id']." ".$row['field_type']." Due ".$row['field_target'];
$record_id = $row['record_id'];
$emailBody .= "Employee: ".$row['field_id']."
Field Type: ".$row['field_type']."
Start Date: ".$row['date_start']."
Target Field: ".$row['field_target']."
Email: ".$row['email_to']." \n";
}
{
$result = mysql_query("UPDATE tablexyz SET email_sent='1' , email_log_date=date('Y-m-d') WHERE record_id='$record_id'");
}
mail($to, $subject, $emailBody);
if (mail($emailto, $emailsubject, $emailBody)) {
echo("<p>Message successfully sent! Record '$record_id'.</p>");
} else {
echo("<p>Message delivery failed...</p>");
}
?>
===========================================================