Q:

how to get sum on every loop on the table

I have a problem on breaking down the amount of the given payment, I think i was missing something on my code. This is my table below.
If i have payment of 5,000, it will deduct on the first row and the remaining sum will send to the 2nd row.
//this is the payment
$payment = 5000;
$temp = '';

//the loop of function
$data = payment_breakdown();
foreach ($data as $row) {

    $amount = $row['AMOUNT'] - $payment."\n";
}

//handle the difference of every loop of the function
$temp = $amount;

//result of the amount
echo $amount;

//this is my function to get the data from the table
function payment_breakdown(){
    $db = database2();
    $query = "SELECT AMOUNT FROM TABLE1";
    $cmd = $db->prepare($query);    
    $cmd->execute();
    $rows = $cmd->fetchAll();
    $db = null;

    return $rows;
}

supposedly if the amount on the table is this
Data From Table | The Payment
        3000    |     3000
        3000    |     2000

A:

You could do it in SQL:
SELECT 
  amount, 
  paid,
  sum(amount-paid) open
FROM
  payment 
GROUP BY amount, paid 
WITH ROLLUP
HAVING 
  amount IS NULL
  OR paid IS NOT NULL
;

Based on the data
INSERT INTO payment (amount, paid)
VALUES 
(3000,3000), 
(3000,2000),
(4000,1000)
;

you get
amount;paid; open
3000  ;2000; 1000
3000  ;3000; 0
4000  ;1000; 3000
NULL  ;NULL; 4000

Or you might want a simple substraction from a deposit:
SET @credit := 5000;

SELECT 
  amount, 
  @credit := @credit-amount credit  
FROM payment 
;

SELECT @credit;

However, in the latter case you should rather store all payments and amounts to pay into database tables and sum up all together. Consider refactoring your database structure design.

