duanmuybrtg1231 2017-04-20 16:51
浏览 120
已采纳

电子邮件中的foreach循环问题

I'm having difficulty getting a foreach loop to function correctly when generating an email. I've searched for answers and I've found directions to insert a foreach loop into an email, but nothing about the loop not working.

I'm trying to email order receipts to customers after they place an order, and everything in the email gets delivered except for the list of items.

I'll try to include as much of my logic as possible: When the order is placed, the array of shopping cart items is serialized and then stored in the database. After the payment processor returns that the payment was successful, I display a receipt page on the website which the user can print. The order items are retrieved from the database as follows:

$stmt = $dbh->prepare("SELECT * FROM *table* WHERE orderID = :q0")
$stmt->bindValue(":q0",$orderNum)
$stmt->execute();
foreach($stmt as $row) {
    $items = unserialize($row['order_contents']);
}

at this point, if I echo $items, I see an array of the items from the order. So far, so good.

Now because I'm using PDO, a foreach loop within the query isn't something I've figured out how to do. Instead, I've initialized a variable to hold the items from the foreach loop:

foreach($items as $prod_id => $value) {
    $q .= $prod_id . ',';
}
$q = substr($q, 0, -1);

This stores the array in a variable which I can now use in the PDO statement for the next query:

$stmt2 = $dbh->prepare("SELECT * FROM *productTable* WHERE prod_ID IN ($q)");
$stmt2->execute();
foreach($stmt2 as $row) {
$itemName = htmlentities(strip_tags($row['prod_name']));
$id = htmlentities(strip_tags($row['prod_ID']));
$qty = htmlentities(strip_tags($items[$prod_id]['quantity']));
$price = $items[$prod_id]['price'];
echo "
    <tr>
        <td>".$qty."</td>
        <td>".$itemName."</a></td>
        <td>".$price."</td>                        
    </tr>";
} // THIS CODE WORKS. I can see each item from the order as a new row in the table

Once again, so far so good. I can run a foreach loop to echo the items to the page, and they all display with the proper item name as well as other information from the table which I left out from this example.

Skip ahead to the end of the file, and I've got the following script which does not work and I can't figure out why. The email sends successfully, but none of the products from the foreach loop show up in the email.

$to = 'user@email.com'
$subject = 'Your order receipt for order '.$orderNum
$headers = 'From: orders@website.com'."
".
           'Reply-To: orders@website.com'."
".
           'Content-Type: text/html; charset=UTF-8'."
".
           'X-Mailer: PHP/'.phpversion();
$message =  '<html><body>';
$message .= '<h2>Thanks for your purchase!</h2><br>';
$message .= '<p>Here are the details of your order number '.$orderRef.':<br><table>';
$message .= '
<tr style="width: 100%;">
    <th scope="col" style="width: 20%;">Quantity:</th>
    <th scope="col" style="width: 60%;">Name:</th>
    <th scope="col" style="width: 20%;">Price:</th>
</tr>
';
foreach ($stmt2 as $row) {
    $message .= "
    <tr>
        <td>".$qty."</td>
        <td>".$itemName."</td>
        <td>".$price."</td>                        
    </tr>"; //THIS CODE DOESN'T WORK, Even though it's using the same variables as the loop from above. 
}
$message .= '</table><br>';
$message .= 'If you have any questions about your order, please call us at <b>XXX-XXX-XXXX</b>';
$message .= '</body></html>';
mail($to, $subject, $message, $headers);

The email sends, and I see everything before and after the foreach loop, but I don't see the actual items being generated. After the email code, I can echo the variables to the page and they all display properly, so the variables are still declared.

Additional information which may or may not be relevant: I'm trying to execute this code on a freshly imaged VPS with Ubuntu 14.04. I just installed an SSL certificate on Monday I installed UFW on my VPS recently. SMTP, IMAP, and UTP ports are not blocked. PHP version 5.5.9-1ubuntu4.21

Here's a screenshot of the email output:screen capture of email

Edit: The variables were already defined after the first foreach($stmt2 as $row) statement. I've added the additional code to reflect this.

  • 写回答

3条回答 默认 最新

  • dongxiao1591 2017-04-20 16:58
    关注

    $stmt2 isn't an array, it's a generator. Among other things, this allows to only load rows into memory as needed, rather than needing to read the whole thing into memory at once.

    The catch is, you can't foreach it twice. You will need to convert it to an actual array. I haven't tested but you may be able to do this with $itemdata = iterator_to_array($stmt2) - failing that just $itemdata[] = $row inside your first foreach will allow you to refer to this $itemdata array later.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的算法代码
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据