I have a mysql select statement that returns 5 rows. The results go into a while loop and then called against the fetch_assoc() function. At the end of this loop I have an include for phpEmailer. The problem is that although 5 rows are returned in the select statement only the first row sends out an email. Here is my code:
include "../includes/myDBConn.php";
require_once '../includes/PHPMailer/PHPMailerAutoload.php';
$sql="SELECT A.client, A.clientid, A.location, DATE_FORMAT(A.GoLiveDate, '%m/%d/%Y') AS
GoLiveDateFormat,
A.ProgressStatus, B.SystemEngineer, C.emailAddress FROM customerinfo A
INNER JOIN projectteam B
ON A.clientid = B.ID
left JOIN engineers C on B.SystemEngineer=C.engName
WHERE Live NOT IN (1,2)
AND GoLiveDate < NOW() OR GoLiveDate is null";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$client = $row['client'];
$engEmail = $row['emailAddress'];
$SystemEngineer = $row['SystemEngineer'];
include '../includes/PesterEmailer.php';
}
}
What is going wrong? It seems to me that for each row and seperate email should be sent because the emailer is called each time. Is this the way?
My Answer:
The issue might be with the way you are including the PHP emailer script inside the loop. Instead of including the emailer script inside the loop, you can create an array of email data for each row and then send all the emails outside the loop.
Here's an example of how you can modify your code:
php
include "../includes/myDBConn.php";
require_once '../includes/PHPMailer/PHPMailerAutoload.php';
$sql = "SELECT A.client, A.clientid, A.location, DATE_FORMAT(A.GoLiveDate, '%m/%d/%Y') AS GoLiveDateFormat, A.ProgressStatus, B.SystemEngineer, C.emailAddress FROM customerinfo A INNER JOIN projectteam B ON A.clientid = B.ID left JOIN engineers C on B.SystemEngineer=C.engName WHERE Live NOT IN (1,2) AND GoLiveDate < NOW() OR GoLiveDate is null";
$result = $conn->query($sql);
$emailData = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$client = $row['client'];
$engEmail = $row['emailAddress'];
$SystemEngineer = $row['SystemEngineer'];
$emailData[] = array(
'client' => $client,
'engEmail' => $engEmail,
'SystemEngineer' => $SystemEngineer
);
}
}
foreach ($emailData as $data) {
$client = $data['client'];
$engEmail = $data['engEmail'];
$SystemEngineer = $data['SystemEngineer'];
// Include the emailer script here or call the email sending function
include '../includes/PesterEmailer.php';
}
By creating an array of email data inside the loop and then sending all the emails outside the loop, you ensure that each row's email data is stored and processed separately. This should help in sending separate emails for each row in the result set.
Rate this post
3 of 5 based on 5502 votesComments