Hi there i have a problem with my cart calculations in a website i am making and it only displays the last price of the item i add to tthe cart instead of the total of all items added

<?php 

     $select_cart = mysqli_query($conn, "SELECT * FROM `cart`");
     $grand_total = 0;
     if(mysqli_num_rows($select_cart) > 0){
        while($fetch_cart = mysqli_fetch_assoc($select_cart)){
     ?>

     <tr>
        <td><img src="uploaded_img/<?php echo $fetch_cart['image']; ?>" height="100" alt=""></td>
        <td><?php echo $fetch_cart['name']; ?></td>
        <td>KSH<?php echo number_format($fetch_cart['price']); ?>/-</td>
        <td>
           <form action="" method="post">
              <input type="hidden" name="update_quantity_id"  value="<?php echo $fetch_cart['id']; ?>" >
              <input type="number" name="update_quantity" min="1"  value="<?php echo $fetch_cart['quantity']; ?>" >
              <input type="submit" value="update" name="update_update_btn">
           </form>   
        </td>
        <td>KSH<?php echo $sub_total = number_format($fetch_cart['price'] * $fetch_cart['quantity']); ?>/-</td>
        <td><a href="cart.php?remove=<?php echo $fetch_cart['id']; ?>" onclick="return confirm('remove item from cart?')" class="delete-btn"> <i class="fas fa-trash"></i> remove</a></td>
     </tr>
     <?php
       $grand_total = $sub_total;  
        };
     };
     ?>

Dani AI

Generated

Short version: the cart loop should keep calculations in numeric form, accumulate a numeric subtotal into a numeric grand total, and only apply number_format() when printing values. As shows, the current code formats the per-row value into a string and then overwrites $grand_total each iteration. is correct to point out both problems; the following is a compact, safer pattern and a few debugging checks.

<?php
$grand_total = 0.0;
$select_cart = mysqli_query($conn, "SELECT * FROM `cart`");
while ($item = mysqli_fetch_assoc($select_cart)) {
    $price = (float) $item['price'];       // force numeric
    $qty   = (int)   $item['quantity'];    // force integer
    $line_total = $price * $qty;           // numeric math
    $grand_total += $line_total;           // accumulate (numeric)

    // output: format only for display
    echo '<td>KSH ' . number_format($line_total, 0) . '/-</td>';
}
echo '<tr><td colspan="4">Grand total: KSH ' . number_format($grand_total, 0) . '/-</td></tr>';
?>

Debug checklist

  • var_dump($item['price'], $item['quantity']) to confirm the raw types coming from the DB.
  • Remove any number_format() from inside calculations; it converts numbers to strings.
  • Ensure $grand_total is initialized to a numeric value (0 or 0.0).
  • If prices arrive with symbols/commas (e.g., "KSH 1,000"), strip non-numeric chars before casting: preg_replace('/[^\d.]/','', $priceRaw).

Best-practice notes

  • Store currency as a DECIMAL(10,2) or as integer cents in the database to avoid float surprises.
  • Always validate $_POST quantities on the server with (int) and sane bounds.
  • Keep display formatting and escaping (htmlspecialchars) separate from arithmetic.

Following those steps will reproduce the fix that suggested while making the calculation robust and easier to debug.

Recommended Answers

All 3 Replies

There are two reasons why you are not getting the correct calculation for grand total. First, $sub_total is a string, not a number. Why? Because you are assigning to it a string, which results from using number_format() on $fetch_cart['price'] * $fetch_cart['quantity']. Second, even if $sub_total is not a string, you are replacing the value of $grand_total with $sub_total, without first adding $sub_total to it.

Try this (not tested):

Line 20: Assign the value of $fetch_cart['price'] * $fetch_cart['quantity'] to $sub_total and then apply number_format() on that value:

<td>KSH<?php echo number_format($sub_total = $fetch_cart['price'] * $fetch_cart['quantity']) ?>/-</td>

Line 24: Add the value of $sub_total (now properly a number value) to $grand_total:

$grand_total += $sub_total;

Coding suggestions:

  1. Use PHP short echo tags <?= ?> instead of <?php echo '' ?>
  2. Semicolons after closing brackets } are unnecessary.
commented: Thank you for your help, i tested the code and it fairly works as when the items are one it displays the total but when i update the number errors +0

What errors are you getting?

commented: It's only adding the items when they are 1 if I update the number it brings non numeric value error I think its because of the concatenation+= +0

Non numeric value error occurs when you try to add a string (e.g., 'people') to a number (e.g., '5'). The += is an addition operator, not a concatenation: see PHP language operators:

$grand_total += $sub_total;

Is the shortcut for:

$grand_total = $grand_total + $sub_total;

For the shortcut to work, both values must be numerical. Of course, the same applies to the long version. If either $grand_total or $sub_total are not numerical values, the operation will fail.

So if your code is not working, it means that one of the values you are trying to add is non numerical. Which one is it? Without more details, there isn't much else I can do to help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.