Search code examples
phpsqlmailer

PHP - Script repeating when outside foreach statement


I have an issue with a script I have written that simply selects entries from a database and sends an email to the user to update them on the entries relevant to them. The emailer function is working as is the entries filtering out to the individual users. However I'm having a problem where the email is being sent the same number of times the entries appear in the database. The email contains the same content (all 4 entries appear in the same email but it sent 4 times as an example).

this is the mailing script:

$data = getData(); 
$uniqueUsers = array();

foreach($data as $item){
$user = $item[1];
$name = $item[3];
$array = array($user, $name);

if(!in_array($array, $uniqueUsers)){
    array_push($uniqueUsers, $array);
};
};
echo print_r($uniqueUsers);
echo "<br>";
echo "<hr>";

foreach($uniqueUsers as $user){
$email = $user[0];
$name = $user[1];
$fullName = explode(" ", $name);
$firstName = $fullName[0];
$updates = "";
echo $email;
echo "<br>";
echo $name;
echo "<br>";
foreach($data as $item){
    if($user[0] == $item[1]){
        $equipmentName = $item[0];
        $approved = $item[2];
        $start = $item[5];
        $end = $item[6];
        $updates .= $approved . " - " . $equipmentName . " (Booked from " . date('l, jS F', strtotime($start)) . " to " . date('l, jS F', strtotime($end)) . ")";
        $updates .= "<br>";
    };
};
echo $updates;
echo "<hr>";

mailer($email, $firstName, $updates);
};

This is the getdata() script:

mysql_select_db("WBLResources", $con) or die ("Error selecting specified database on mysql server: ".mysql_error());

$query = "SELECT * FROM `Bookings` WHERE `updated` > '" . $date . "'";

$result = mysql_query($query);

$numOfRows = mysql_num_rows($result); 

if($numOfRows < 1){
    exit();
};

for ($i = 0; $i < $numOfRows; $i++) { 
    $row = mysql_fetch_array($result); 
    $result_array[$i] = array($row["equipment_name"], 
                              $row["user"], 
                              $row["approved"], 
                              $row["name"], 
                              $row["updated"], 
                              $row["start"], 
                              $row["end"]);
}; 

return $result_array;
};

From my analysis the mailer() function should run on uniqueUsers array. This is a snippet of that which I pulled in 10 minutes ago:

Array ( 
       [0] => Array ( 
                      [0] => 
                      [1] => ) 
       [1] => Array ( 
                      [0] => ####@###.co.uk 
                      [1] => Username ) 
       [2] => Array ( 
                      [0] => ####@###.co.uk 
                      [1] => Username ) 
       [3] => Array (  
                      [0] => #####@###.co.uk 
                      [1] => Username ) 
       [4] => Array (  
                      [0] => #####@###.co.uk 
                      [1] => Username ) 
       [5] => Array ( 
                      [0] => ######@###.co.uk  
                      [1] => Username ) 
       [6] => Array ( 
                      [0] => #####@###.co.uk 
                      [1] => Username ) )

Mailer function:`function mailer($email, $firstName, $updates){

$mail = new PHPMailer;

$subject = "Resource Bookings";

$htmlMessageBody = "<div style=font-size:10.0pt;font-family:'Arial',sans-serif;color:black;mso-fareast-language:EN-GB'>Dear " . $firstName . ",<br><br>The following resource bookings have been updated: <br><br>" . $updates . "<br><br>Many thanks,<br>TSW Support</div>";

//$mail->SMTPDebug = 3;                               // Enable verbose debug output

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = '#######';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '###@####.co.uk';                 // SMTP username
$mail->Password = '######';
$mail->SMTPSecure = 'tls';
$mail->Port = 25;                                    // TCP port to connect to
//$mail->SMTPDebug = 3;

$mail->setFrom('####@#####.co.uk', 'TSW Training Group');
$mail->addAddress($email, $firstName);     // Add a recipient
$mail->addReplyTo('#####@######.co.uk', 'TSW Training Group');
$mail->addCC("#####@#####.co.uk", "Support");

$mail->isHTML(true);                                  // Set email format to HTML

$mail->Subject = $subject;
$mail->Body    = $htmlMessageBody;
//$mail->AltBody = $plainMessageBody;

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
};  

};`

Any help would be appreciated?


Solution

  • This logic should fix your problem. Haven't tested it though, so let me know if you hit any errors.

        $user_lists = array();
        foreach($data as $item){
        $user = $item[1];
        $name = $item[3];
        $array = array($user, $name);
    
        if(!in_array($user, $user_lists)){
            array_push($uniqueUsers, $array);
            $user_lists[] = $user;
        };
        };
    

    Hope this helps!