0

I'm having an issue with with a PHP function displaying multiple sums instead of just one when I use array_sum. I'm using phpMyAdmin and the two database tables for this function. These are the tables:

games:

enter image description here

cart:

enter image description here

function total_price() {
    $total = 0; 
    global $con; 
    $ip = getIP(); 
    $select_price = "select * from cart where ip_add = '$ip'"; 
    $run_price = mysqli_query ($con, $select_price);
    while ($g_price = mysqli_fetch_array($run_price)) { 
        $Cart_Game_ID = $g_price['g_ID']; 
        $cart_price = "select * from games where Game_ID = '$Cart_Game_ID'";    
        $run_game_price = mysqli_query($con, $cart_price); 
        while($pp_price = mysqli_fetch_array($run_game_price)){
            $Game_Price = array($pp_price['Game_Price']);  
            $values = array_sum($Game_Price);
            $total += $values; 
        }
    echo "$" . $total; 
    }

}

Every game in my database costs $20. There are currently 5 games in my database. When I run this function I get $20$40$60$80$100. All i need is the $100. Not the previous 4 sums.

2
  • Is this just for learning purposes? Otherwise, the sum calculation could be done with only one database query, with no loops, ... Commented Mar 12, 2015 at 22:51
  • Yea its to help understand how loops can be used to pull data from multiple databases. Commented Mar 12, 2015 at 23:01

1 Answer 1

2

Move this outside the While Loop:

echo "$" . $total;
Sign up to request clarification or add additional context in comments.

2 Comments

Haha your welcome - I know exactly how you feel, all it takes is a fresh pair of eyes
@underflow Haha, that's the programmer destiny xD

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.