Search code examples
phpmysqlphpmailerpsql

How to send information from SQL table by using phpmailer?


I have a SQL table that shows the expiry date of the items, and I want to send the status of the expiration date on a daily basis through email, where I want the user to know the expiration date update for the listed items.

I tried to use this example in phpmailer, by using localhost and it works, but I do not know how to link that with my case.

For example, is it possible to do like this $body= include ('sql.php'); or is there other way to do that?, where I am only interested in sending the Expiry Date and Expiration Message from this table, and is it possible to send the entire table?

Here is the SQL code

<?php

 $con=mysqli_connect('localhost','','','arduino');

 if(mysqli_connect_errno($con))
 {
    echo 'Failed to connect:'.mysqli_connect_error();
}
else
    echo 'Connected Successfully!! </br>';
$url=$_SERVER['REQUEST_URI'];
$sql = "SELECT 
    ID,
    Item_Name,
    Expiry_Date,
    CASE 
        WHEN `Expiry_Date` < CURDATE() THEN CONCAT(`Item_Name`,' has EXPIRED already')
        WHEN `Expiry_Date` = CURDATE() THEN CONCAT(`Item_Name`,' will expire today')
        WHEN `Expiry_Date` BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' will expire tomorrow')
        WHEN `Expiry_Date` > DATE_ADD(CURDATE(), INTERVAL 1 DAY) THEN CONCAT(`Item_Name`,' has not expire yet')
        ELSE 'Error processing expiration date.'
   END AS `Expiration_Message`
FROM
    test;";

    $result = mysqli_query($con,$sql);


    while($row = mysqli_fetch_array($result)){
        echo ($row['Expiration_Message']);
        echo '<br>';
    }

    print_r($row);

    mysqli_close($con);

?>

And here is the code that I took it from phpmailer example

<?php
// Import PHPMailer classes into the global namespace
// These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

//Load composer's autoloader
require 'vendor/autoload.php';

$mail = new PHPMailer(true);                              // Passing `true` enables exceptions
try {
    //Server settings
    //$mail->SMTPDebug = 1;                                 // Enable verbose debug output
    $mail->isSMTP();                                      // Set mailer to use SMTP
    $mail->Host = 'Smtp.live.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth = true;                               // Enable SMTP authentication
    $mail->Username = '[email protected]';                 // SMTP username
    $mail->Password = 'XXXXX';                           // SMTP password
    $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
    $mail->Port = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('[email protected]', 'Smart Fridge');
    $mail->addAddress('[email protected]', 'Joe');     // Add a recipient
    $body= '<p><td><strong>Hello</strong></td> this is my first email!!!!</p>';

    //Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Expiry Date';
    $mail->Body    = $body;
    $mail->AltBody = strip_tags($body);

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

Solution

  • You need to store your result into a variable, not echo it.

    $mailBody = '';
    
    while($row = mysqli_fetch_array($result)){
        $mailBody .= $row['Expiration_Message'] . "<br>\n";
    }
    

    and later

    $mail->Body    = $mailBody;
    

    .= is an operator to concatenate your strings. It is equal to:

    $mailBody = $mailBody . 'something new string to concat';