我想将我所购买的所有产品邮寄给我的客户,以免。所以我的查询按照ord_product表中的订单ID选择产品。
我的 ord_product 表格结构和条目是:
id | product_id | order_id | name | quantity | price
______________________________________________________________
1 | 100 | 1000 | Monopoly | 2 | 5.00
2 | 101 | 1000 | Chases | 1 | 20.00
现在我的问题是在我的脚本之后它在客户端电子邮件中显示我的第一个产品Monopoly 2次。
这是我的ord_product查询
$rt = mysqli_query($dbh,"SELECT * FROM ord_product WHERE order_id='$o_id'") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_assoc($rt)) {
$newrow[$row['id']]['id'] = $row['id'];
$newrow[$row['id']]['product_id'] = $row['product_id'];
$newrow[$row['id']]['name'] = $row['name'];
$newrow[$row['id']]['quantity'] = $row['quantity'];
$newrow[$row['id']]['price'] = $row['price'];
foreach($newrow as $array){
$subtotal = ($array['price']*$array['quantity']);
//echo result at mail
$message .= "<p><b>Name : </b>".$array['name']." <span><b>Qty : </b>".$array['quantity']." pcs </span><span><b>Price : </b>AUD ".$array['price']." </span><span><b>Total : </b>AUD ".$subtotal." </span></p>";
mysqli_query($dbh,"UPDATE allproduct SET sold=sold+1 WHERE id= '".$array['product_id']."'");
}
}
在我的客户电子邮件中发送回信:
Name: Monopoly Qty : 2 Price : 5.00 Total : AUD 10.00
Name: Monopoly Qty : 2 Price : 5.00 Total : AUD 10.00 // echo again
Name: Chases Qty : 1 Price : 20.00 Total : AUD 20.00
答案 0 :(得分:0)
试试这段代码
$rt = mysqli_query($dbh,"SELECT * FROM ord_product WHERE order_id='$o_id'") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_assoc($rt)) {
$subtotal = ($row ['price']*$row ['quantity']);
$message .= "<p><b>Name : </b>".$row ['name']." <span><b>Qty : </b>".$row ['quantity']." pcs </span><span><b>Price : </b>AUD ".$row ['price']." </span><span><b>Total : </b>AUD ".$subtotal." </span></p>";
mysqli_query($dbh,"UPDATE allproduct SET sold=sold+1 WHERE id= '".$row ['product_id']."'");
}
}
答案 1 :(得分:0)
将foreach循环保持在while循环之外。完成while
循环后,而不是启动foreach
循环。如果你保持while循环而不是在每个循环中附加到$message
。完成while
循环后的最佳做法,而不是启动foreach
循环。
$rt = mysqli_query($dbh,"SELECT * FROM ord_product WHERE order_id='$o_id'") or die(mysqli_error($dbh));
while ($row = mysqli_fetch_assoc($rt)) {
$newrow[$row['id']]['id'] = $row['id'];
$newrow[$row['id']]['product_id'] = $row['product_id'];
$newrow[$row['id']]['name'] = $row['name'];
$newrow[$row['id']]['quantity'] = $row['quantity'];
$newrow[$row['id']]['price'] = $row['price'];
}
foreach($newrow as $array){
$subtotal = ($array['price']*$array['quantity']);
//echo result at mail
$message .= "<p><b>Name : </b>".$array['name']." <span><b>Qty : </b>".$array['quantity']." pcs </span><span><b>Price : </b>AUD ".$array['price']." </span><span><b>Total : </b>AUD ".$subtotal." </span></p>";
mysqli_query($dbh,"UPDATE allproduct SET sold=sold+1 WHERE id= '".$array['product_id']."'");
}