在一封电子邮件中发送多行

时间:2015-03-14 18:44:14

标签: php mysql email

我希望能够将数据库中的多行发送到一封电子邮件中。到目前为止,我得到的是两封(或更多)电子邮件,每封包含一行。如何将所有内容都收录到一封电子邮件中?

这是我的代码。将mail()保留在while循环之外只会给我最后一个条目。将它保留在while循环中会发送两封电子邮件。

        $sql = "SELECT productid, kind, qty, price, GROUP_CONCAT(product) as product FROM orderitems LEFT JOIN Products ON orderitems.code = Products.productid WHERE orderitems.customerid = $customerid GROUP BY productid";
        $result = mysqli_query($db, $sql) or die(mysqli_error($db));
        while($row = mysqli_fetch_array($result)) {
          $product = $row['product'];
          $productid = $row['productid']; 

          $to = "email@gmail.com";
          $subject = "Order";
          $emailBody = "ID: ".$product."\n"."Product: ".$productid."\n";
          $emailBody .= "Total: ".$total."\n";
          $headers = 'From: Email <no-reply@someemailaddress>' . "\r\n" .
              'Reply-To: someemailaddress' . "\r\n" .
              'X-Mailer: PHP/' . phpversion();
          mail($to, $subject, $emailBody, $headers); }
如果有人能给我一个正确方向的推动,我会很高兴的!

2 个答案:

答案 0 :(得分:1)

我想你只想重复这个字符串。

ID: ".$product."\n"."Product: ".$productid."\n";

所以它应该是循环而其他不应该。像:

$sql = "SELECT productid, kind, qty, price, GROUP_CONCAT(product) as product FROM orderitems LEFT JOIN Products ON orderitems.code = Products.productid WHERE orderitems.customerid = $customerid GROUP BY productid";
$result = mysqli_query($db, $sql) or die(mysqli_error($db));

$emailBody = '';
$total = 0;//I dont know what is total for you

while($row = mysqli_fetch_array($result)) {
    $product = $row['product'];
    $productid = $row['productid']; 

    $emailBody .= "ID: ".$product."\n"."Product: ".$productid."\n";
    $total = $total + 1; //Just for example

}
$to = "email@gmail.com";
$subject = "Order";
$emailBody .= "Total: ".$total."\n";
$headers = 'From: Email <no-reply@someemailaddress>' . "\r\n" .
     'Reply-To: someemailaddress' . "\r\n" .
     'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $emailBody, $headers); 

答案 1 :(得分:0)

问题是你在while循环中有mail()函数,所以对于每个循环,函数都会发送一封电子邮件。
你可以从循环中提取mail(),只收集你在循环中需要的行,如下所示:

    $emailBody = '';
    while($row = mysqli_fetch_array($result)) {
      $product = $row['product'];
      $productid = $row['productid']; 
      $emailBody .= "ID: ".$product."\n"."Product: ".$productid."\n";
      $emailBody .= "Total: ".$total."\n";
    }

    $to = "email@gmail.com";
    $subject = "Order";          
    $headers = 'From: Email <no-reply@someemailaddress>' . "\r\n" .
          'Reply-To: someemailaddress' . "\r\n" .
          'X-Mailer: PHP/' . phpversion();
    mail($to, $subject, $emailBody, $headers); }