我希望能够将数据库中的多行发送到一封电子邮件中。到目前为止,我得到的只是两封(或更多)电子邮件,每封电子邮件包含一行。如何将所有内容放入一封电子邮件中?
这是我的代码。将 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); }
如果有人能把我推向正确的方向,我会很高兴!
我认为你只想重复这个字符串。
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);
问题是你在 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); }