【发布时间】:2020-07-24 10:17:53
【问题描述】:
我如何获得我使用 PHP 选择的产品总量,下面是我的代码和我添加的 sum_total = 0 变量,以对我的代码选择的产品总量求和,但结果得到不同的值。
<?php
// products
$products = "";
$sum_total = 0;
$select_products = "SELECT * FROM products ORDER BY time_added DESC";
$stmt = mysqli_prepare($db, $select_products);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// fetch results
$product_id = $row["product_id"];
$product_name = $row["name"];
$product_amount = $row["amount"];
// product img
$select_product_img = "SELECT images FROM product_images WHERE for_product_id = ?";
$stmt = mysqli_prepare($db, $select_product_img);
mysqli_stmt_bind_param($stmt, "i", $product_id);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $product_img);
while (mysqli_stmt_fetch($stmt)) {
// fetch results
}
$products .= '
<div class="col-xl-3 col-lg-4 col-md-4 col-12">
<div class="single-product">
<div class="product-img">
<a href="../product/'.$product_id.'">
<img class="default-img" src="../images/products/'.$product_img.'" alt="#">
<img class="hover-img" src="../images/products/'.$product_img.'" alt="#">
</a>
</div>
<div class="product-content">
<h3><a href="../product/'.$product_id.'">'.$product_name.'</a></h3>
<div class="product-price">
<span>$'.number_format($product_amount).'</span>
</div>
</div>
</div>
</div>';
// total amount of products
echo $sum_total += $product_amount;
}
?>
【问题讨论】:
-
您的意思是要累计
$row["amount"]的总数还是想知道有多少产品被选中?不是很清楚 -
现在你在
$sum_total得到了什么? -
显示总数将回声移出循环!但是将累积
$sum_total += $product_amount;留在循环内 -
与问题无关,但您可以使用
join(如果不是所有产品都有图像,则可以左连接)并结合product_images查询,因此只需要1 个select。 -
我想获取@KUMAR 选择的所有产品的总金额
标签: php