2012-01-11 67 views
-1

我在我的php代碼下面有str_replace奇怪的問題。應該發生的是,在每個循環中,它應該用{name}替換數據庫中的人名。實際上,如果我郵寄兩個人,第一個用他們的名字替換,他們會收到一封電子郵件dear, bob bla bla bla。第二個似乎總是dear , {name} bla bla bla。就好像在第二個循環中,有什麼失敗?奇怪的小故障str_replace在我的php腳本

  <?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('[email protected]', 'Chandlers Oil & Gas'); 
          $mail->AddReplyTo('[email protected]', '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(); 
      } 
      ?> 
+0

不應該在循環中使用臨時$ body,以防止覆蓋原始$ body模板嗎? – pritaeas 2012-01-11 09:45:32

回答

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()

+0

嗨,我嘗試使用頂級示例,現在我只在所有電子郵件上親愛的{name}? – 2012-01-11 10:00:00

+0

嗯。那麼你實際上必須使用那個新的臨時變量。 '$ mail-> MsgHTML($ bodyTemp);' – 2012-01-11 10:25:57

+0

這對第一封電子郵件起作用,然後第二封電子郵件現在只是{message}而沒有其他內容? – 2012-01-11 10:41:38

0

在循環之前,$ body可能包含Dear {name}。然後你循環一次,然後它包含Dear Iain。然後在第二個循環中,不再有{name}來替換。

+0

嗨,我該如何做到這一點,因爲使用下面的示例只會在每封電子郵件中給我{姓名}:-S – 2012-01-11 10:21:49