user4651092
user4651092

Reputation:

How to add values to a single variable in while loop in php

I would like to add the price values to a total_price and echo it.

My code takes values from session and makes a mysql query to take information from database tables. Once I have it, it shows the prices of each row. Now I'm adding a total price, but instead of taking the values of all prices and add them, it takes the values of the last row only. I would like that total_price to add all the values $price. Here is the code:

<?php 
if (empty($_SESSION['cart'])) { echo "Nothing here";} else {
$whereIn = implode(',', $_SESSION['cart']);

$list_query = mysqli_query($con,"SELECT * FROM packages WHERE id IN ($whereIn)"); 
while($run_list = mysqli_fetch_array($list_query)){
$id = $run_list['id'];
    $price = $run_list['package_price'];  
    $title = $run_list['package_title'];  


    $total_price = '';
$total_price += $price ;




echo '<p> Product :',$title,' | Price: ',$price; ?> <a href="add_to_cart/remove_from_cart.php?id=<?php echo $id; ?>">Remove item</a></p> 

<?php 

}?>  

<p> Total Price: <?php echo $total_price;?></p>

<p> <button> Checkout </button></p>

<?php } ?>

Upvotes: 2

Views: 7011

Answers (5)

S1arl
S1arl

Reputation: 55

$total_price ='';
while {
$total_price += $price
}

Your total_price eq price every time the loop is iterating

Upvotes: 0

clean_coding
clean_coding

Reputation: 1166

Try like this:

$total_price = 0;
while($run_list = mysqli_fetch_array($list_query)){
   $price = $run_list['package_price']; 
   $total_price += $price;
}

Upvotes: 3

Martin Currah
Martin Currah

Reputation: 517

Your total price variable is getting reset on each iteration. Initialise the variable outside of the loop.

$total_price = 0;

while($run_list = mysqli_fetch_array($list_query)){
    $id = $run_list['id'];
    $price = $run_list['package_price'];  
    $title = $run_list['package_title'];  
    $total_price += $price ;

    ...
}

Upvotes: 1

Kisaragi
Kisaragi

Reputation: 2218

$total_price += $price;

You are currently resetting $total_price each time you iterate.

Upvotes: 2

Bart
Bart

Reputation: 1268

Put $total_price = ''; over while loop

Upvotes: 4

Related Questions