通过电子邮件发送的PHP购物车订单仅显示最后订购的产品,而不是每个订购的产品

时间:2017-03-01 18:46:34

标签: php

我正在玩PHP购物车,我正试图通过电子邮件将订单发送给卖家。

我的问题是,如果订购了多个商品,那么实际上只会在电子邮件中发送最后一个商品,但是当我回显时,会显示所有商品。

你能解释一下为什么会这样吗?

if(isset($_SESSION["products"])){
$total = 0;
$cart_items = 0;
foreach ($_SESSION["products"] as $cart_itm){
$product_code = $cart_itm["code"];
$results = $mysqli->query("SELECT product_name,product_desc, price FROM products WHERE product_code='$product_code' LIMIT 1");
$rows = array();
while ($obj = $results->fetch_object()){

$rows[] = $obj; 

    echo $rows[0]->product_name.' x '.$cart_itm["qty"].' ; '; // here is ok

    $prod_name = ($rows[0]->product_name); // here only the last product displays. Why?!
}
$subtotal = ($cart_itm["price"]*$cart_itm["qty"]);
$total = ($total + $subtotal);
$cart_items ++;

}
}

$prod_name = str_replace($cyr, $lat, $prod_name);

$random = rand(72891, 92729);
$subject = "New order #$random";        
$message = "You have new order from $name  $lname with adress $curraddr and order details: $prod_name with a total value of $total dollars.";   

$from = "From: admin@mail.xyz";
$to = "mail@mail.com";

mail($to, $subject, $message, $from);

1 个答案:

答案 0 :(得分:1)

每次迭代while循环时,都会覆盖$prod_name。最后一次循环,你用最后一个产品覆盖变量。

至于echo"正在工作,"每次进行循环时,echo的输出都不会被覆盖。相反,你不断追加到上次印刷的结尾。

要将所有产品名称插入电子邮件中,您应该在完成循环时构建消息。尝试阅读string concatenation以了解更多信息。