简体   繁体   中英

Email generated html with dynamic values using php

I have a format simple certificate. The certificate needs to be populated with values from the database and emailed. Below is the quick fix I did. The problem is the certificates sent are not of one person instead of those queried.

$query ="SELECT  r.email, r.LastName, r.OpNo, 
r.QuizNo From tbl_cert where Pass =1 AND Printed is null;
$result=mysql_query($query);
while( ($row= mysql_fetch_array($result)) ){
            $subject = "CPD Certificate";
    $email = $row['email'];
    $LastName = $row['LastName'];
    $OpNo = $row['OpNo'];
    $TestNo = $row['QuizNo'];

            $headers  = "From: online@example.com";
    $headers = 'MIME-Version: 1.0' . "\r\n"; 
    $headers .= 'Content-type: text/html; 
              charset=iso-8859-1' . "\r\n";

            $mail_body ='<html>...Here its were my my 
            html comes with values from table...</html>';

            if (mail($to, $subject, $mail_body, $headers)){
            $query = "UPDATE `tbl_cert` SET Printed = 1 
               WHERE CertificateNo = "  . $CertificateNo;

            $certresult=mysql_query($query);

            if ($certresult) {

        header('Location:tsCertlist.php');
        }

The problem is how to get the $mail_body to have both html and php within the while loop. My generated form or certificate was the same for the 4 users who had Passed and had not printed their certificate.

create a separate template file which contains your HTML and the places you want to insert a variable / replace something put in something like %REPLACE_FIRSTNAME%

Then use str_replace() to change your replacement vars with the db/input/whatever variables with the data you require.

$mail_body = file_get_contents("templates/emailtemplate.htm");
$mail_body = str_replace("%REPLACE_FIRSTNAME%",value_from_DB,$template);

Sorted and if you ever want to change your layout just edit the template file accordingly.

$certNo = 0;
//get $certNo from data base
$mail_body ='<html>'.$certNo.'</html>';
//send

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM