Reputation: 69
How do I get the total amount of products I have selected using PHP, below is my code and sum_total = 0
variable I have added to sum the total amount of products selected by my code but get different value as result.
<?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;
}
?>
Upvotes: 0
Views: 653
Reputation: 1637
add $sum_total in your loop
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// fetch results
$product_id = $row["product_id"];
$product_name = $row["name"];
$product_amount = $row["amount"];
$sum_total+=$row["amount"];
and echo just sum_total
echo $sum_total;
Upvotes: 2
Reputation: 55798
You need to add $sum_total += $product_amount
within your loop and then only echo summed value
<?php
// ...
$sum_total = 0;
// ...
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
// ...
$product_amount = $row["amount"];
$sum_total += $product_amount;
// ...
}
// total amount of products
echo $sum_total;
?>
Upvotes: 2