在我的php脚本中使用str_replace发生了奇怪的故障

时间:2012-01-11 09:40:44

标签: php mysql str-replace

我在下面的php代码中遇到了str_replace的一个奇怪问题。应该发生的是每个循环它应该用从数据库中提取的人名来替换{name}。它实际上做的是,如果我邮寄两个人,第一个人用他们的名字替换,所以他们收到一封电子邮件dear, bob bla bla bla。第二个似乎总是dear , {name} bla bla bla。好像在第二个循环中,某些东西失败了?

            <?php

                 $formid = mysql_real_escape_string($_GET[token]);
            $templatequery = mysql_query("SELECT * FROM hqfjt_chronoforms_data_addmailinglistmessage WHERE cf_id = '$formid'") or die(mysql_error());
            $templateData = mysql_fetch_object($templatequery);

            $gasoiluserTemplate = $templateData->gasoilusers;
            $dervuserTemplate = $templateData->dervusers;
            $kerouserTemplate = $templateData->kerousers;
            $templateMessage = $templateData->mailinglistgroupmessage;
            $templatename = $templateData->mailinglistgroupname;
                                ?>  
                    <?php
            require_once('./send/class.phpmailer.php');
            //include("class.smtp.php"); // optional, gets called from within class.phpmailer.php if not already loaded

            $mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

            // $body                = file_get_contents('contents.html');

            $body = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <style>#title {padding-left:120px;padding-top:10px;font-family:"Times New Roman", Times, serif; font-size:22px; font-weight:bold; color:#fff;}</style>
            </head>

            <body>
            <div style="background:
                                              none repeat scroll 0% 0% rgb(6, 38,
                                              97); width:780px;">
            <img id="_x0000_i1030" style="padding-left:100px;padding-right:100px;"
                                                  src="http://www.chandlersoil.com/images/newsletter/header.gif"
                                                  alt="Chandlers Oil and Gas"
                                                  border="0" height="112"
                                                  width="580">
                                                  <div id="title">{message}</div>

                                                  </div>
            </body>
            </html>
            ';

                            // $body = preg_replace('/\\\\/i', $body);

                            $mail->SetFrom('crea@cruiseit.co.uk', 'Chandlers Oil & Gas');
                            $mail->AddReplyTo('crea@cruiseit.co.uk', 'Chandlers Oil & Gas');

                            $mail->Subject       = "Your Fuel Prices From Chandlers Oil & Gas";

                            $query  = "SELECT leadname,businessname,email FROM hqfjt_chronoforms_data_addupdatelead WHERE keromailinglist='$kerouserTemplate' AND dervmailinglist='$dervuserTemplate' AND gasoilmailinglist='$gasoiluserTemplate'";
                            $result = mysql_query($query);

                            // Bail out on error 
            if (!$result)  
              { 
                trigger_error("Database error: ".mysql_error()." Query used was: ".htmlentities($query), E_USER_ERROR); 
                die();
               }                                    

            while ($row = mysql_fetch_array ($result)) {
              $mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";

               // THIS PULLS THE CLIENTS FIRST NAME OUT ON EACH LOOP
               $firstname = $row["leadname"];

               //THIS PULLS THE CLIENTS BUSSINESS NAME OUT ON EACH LOOP
               $businessname = $row["businessname"];

               // IF THE FIRST NAME FIELD IS BLANK USE THE BUSINESS NAME INSTEAD
               if ($firstname = '')
               {$name = $row["businessname"];}
               else 
               {$name = $row["leadname"];}

               // THIS REPLACES THE {NAME} IN THE PULLED IN TEMPLATE MESSAGE WITH THE CLIENTS NAME DEFINED IN $name
               $body = str_replace('{name}', $name, $body);

               // THIS REPLACES {fuel} IN THE PULLED IN TEMPLATE WITH THE TEMPLATE NAME (WHICH IS THE TYPE OF FUEL)
               $body = str_replace('{fuel}', $templatename, $body); 

               // THIS REPLACES THE {message} IN THE $body ARRAY WITH THE TEMPLATE MESSAGE HELD IN $templateMessage
               $body = str_replace('{message}', $templateMessage, $body);


              $mail->MsgHTML($body);
              $mail->AddAddress($row["email"], $row["leadname"]);




              if(!$mail->Send()) {
                echo "Mailer Error (" . str_replace("@", "&#64;", $row["email"]) . ') ' . $mail->ErrorInfo . '<br>';
              } else {
                echo "Message sent to :" . $row["full_name"] . ' (' . str_replace("@", "&#64;", $row["email"]) . ')<br>';
              }
              // Clear all addresses and attachments for next loop
              $mail->ClearAddresses();
              $mail->ClearAttachments();
            }
            ?>

2 个答案:

答案 0 :(得分:2)

$body包含邮件的模板。在循环中,将str_replace()的返回值赋给此变量。之后,您不能指望它在下一次迭代时包含原始模板。你必须使用一个临时变量:

while (...) {
   $bodyTemp = str_replace('{name}', $name, $body);
   $bodyTemp = str_replace('{fuel}', $templatename, $bodyTemp);
   // ...
}

另外,为了使您的代码更具可读性,我建议您改为使用strtr()

while (...) {
   $bodyTemp = strtr($body, array(
      '{name}' => $name,
      '{fuel}' => $templatename,
      // ...
   ));
}

这可以节省str_replace()的重复调用。

答案 1 :(得分:0)

在循环之前,$ body可能包含Dear {name}。然后你循环一次,然后它包含Dear Iain。然后在第二个循环中,不再需要{name}替换。