0

I am making an e-commerce website. Where I have to show the total amount of all the product which is in the cart. But when I try to get the total amount of all product so it only shows the price of the last product Here is the code

$result = $query->fetchAll(PDO::FETCH_ASSOC);
$total = 0; 
if($result > 0){   
    foreach($result as $row){ 
        $price = $row['price'];
        $total += intval($price);
    }

Because the price was in varchar in the database so I converted into an int using intval() method and echo $total

 <td class="pro-subtotal"><span><?php echo $total; ?></span></td>

But its showing amount of the last row in the list

2 Answers 2

3

You don't need this code. First of all you do not need if($result > 0). Your variable $result is an array, not a number, so you can't compare it to a number. intval makes very little sense if you use the result in an arithmetic context. Assinging a variable into another variable without doing anything useful with it is pointless so remove $price = $row['price']; too.

What you are then left with is a simple loop with arithmetic addition.

$result = $query->fetchAll(PDO::FETCH_ASSOC);
$total = 0; 
foreach($result as $row){
    $total += $row['price'];
}

This is not the smartest idea, since such operations should be done in SQL not in PHP. Is there any reason why you have to do it in PHP? If not then simply aggregate the values in SQL.

SELECT SUM(price) AS total FROM salesOrders WHERE saleId = ?

Then in PDO fetch a single column only.

$total = $query->fetchColumn();
Sign up to request clarification or add additional context in comments.

Comments

0

I think

if($result > 0){ ... }

should be

if(count($result) > 0){ ... }

4 Comments

But it's still not calculating the sum of all price
@Azeez can you pleas4 post the updated code? and also the query please
Take into account that intval returns 0 in case of error. Maybe 'price' doesn't exist in the array?
@Mochilo for the moment there could be 1000 reasons why it's not working, and until he posts the query, we couldn't know

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.