2

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 } ?>
4
  • Move $total_price = ''; outside the loop... OR do $price[] = $run_list['package_price']; then use php.net/manual/en/function.array-sum.php. Also you current approach may be open to SQL injections.. Commented Jan 11, 2016 at 15:56
  • Thanks to all. All your answers are right. After few days of coding, maybe my brain burned out. I don't know how I did miss this very newbie thing. :) Commented Jan 11, 2016 at 16:01
  • You should look into use prepared statements, with parameterized queries. If remove_from_cart.php SQL acts like this SQL you are going to run into issues. Commented Jan 11, 2016 at 16:03
  • No it doesn't have any sql statement in remove_from_cart.php I have there only code that removes an array value from the session. Commented Jan 11, 2016 at 16:15

5 Answers 5

4

Put $total_price = ''; over while loop

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, you are absolutely right :) How didn't I miss it ? Thanks
3

Try like this:

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

Comments

2
$total_price += $price;

You are currently resetting $total_price each time you iterate.

Comments

1

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 ;

    ...
}

Comments

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

Your total_price eq price every time the loop is iterating

Comments

Your Answer

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