我想把他所有购买的产品寄给我的客户。因此,我的查询通过从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
现在我的问题是,在我的脚本之后,它会在客户电子邮件中显示我的第一个产品专卖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
发布于 2016-01-30 15:28:26
试试这段代码
$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']."'");
}
}
发布于 2016-01-30 15:48:44
保持前循环远离时间循环。完成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']."'");
}
https://stackoverflow.com/questions/35103440
复制相似问题