Search code examples
phpphpmaileremail

How to add while loop into email template


I have a email template which look like this-> it's just an example

require 'PHPMailerAutoload.php';

$mail = new PHPMailer;

$mail->isSMTP();                                      // Set mailer to use SMTP
$mail->Host = 'support.example.com';  // Specify main and backup SMTP servers
$mail->SMTPAuth = true;                               // Enable SMTP authentication
$mail->Username = '[email protected]';                 // SMTP username
$mail->Password = '******';                           // SMTP password
$mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
$mail->Port = 25;                                    // TCP port to connect to

$mail->setFrom('[email protected]', 'example Inc.');
$mail->addAddress($to);     // Add a recipient
$mail->addReplyTo('[email protected]', 'Support');
$mail->addCC($to);
$mail->addBCC($to);

$mail->isHTML(true);                                 

$mail->Subject = "$name has sent you a request";
$mail->Body    = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml" style="width: 100%;min-width: 100%;">
    <head> Head content here</head>

    <body>
  body content goes here
</body>
</html>'; 

$mail->AltBody = 'Please Upgrade Your Browser to view this email';

if(!$mail->send()) {
    header('location:https://www.example.com/404.shtml?error-in-sending-email');
}

Now all i want is to use php while loop to show some data from database into email & send it to user

I tried using like this '.while($fetch = mysqli_fetch_array($content)){.' '.}.' but this gave me error what could be the best way?


Solution

  • You cannot have a loop within a string literal. You need to loop and generate your HTML string piece by piece. For example:

    $html = '
        <html>
            <head>
                <!-- head stuff -->
            </head>
            <body>';
    
    while ( $row = mysql_fetch_assoc( $res ) ) {
        $html .= '<p>' . $row['something'] . '</p>';
    }
    
    $html .= '
            </body>
        </html>';
    

    But clearly that code is ugly, hard to follow, and a nightmare to maintain or modify. You might want to switch up to the alternative control structure syntax and some output buffering:

    ob_start();
    
    ?>
    <html>
        <head>
            <!-- head stuff -->
        </head>
        <body>
            <?php while ( $row = mysql_fetch_assoc( $res ) ): ?>
                <p><?php echo $res['something']; ?></p>
            <?php endwhile; ?>
        </body>
    </html>
    <?php
    
    $html = ob_get_clean();