PHP balance sheet

I make a personal financial program in PHP, and I am fixated on the fact that it should be easy to complete the task - balancing the account.

Transactions are stored in MySQL, each of them has type 1 for output, 2 for deposit. Below is my PHP for account balancing, without reaching the desired amount.

//Get the starting balance
$getStartingBalance = $db->query("SELECT amount FROM startingBalance WHERE id = 1");
$startingBalance = $getStartingBalance->fetch();
$startingBalance = $startingBalance['amount'];
//Balance transactions
    $getAllTransactions = $db->query("SELECT * FROM transactions ORDER BY date");
    while ($balanceEntry = $getAllTransactions->fetch()) {
        $balanceEntryType = $balanceEntry['type'];
        $balanceEntryAmount = $balanceEntry['amount'];
        if ($balanceEntryType == "1") {
            $accountBalance = $startingBalance - $balanceEntryAmount; 
        } else if ($balanceEntryType == "2") {
            $accountBalance = $startingBalance + $balanceEntryAmount;
        }
    }

Any ideas? Thanks

+3
source share
2 answers

$accountBalance = $startingBalance - $balanceEntryAmount;

This means that every time you press this line, you set the current balance to the original balance minus the amount of input. You probably want to assign before the while loop:

# or just rename $startingBalance to $accountBalance
$accountBalance = $startingBalance;

and then in the while loop

$accountBalance = $accountBalance - $balanceEntryAmount;

Of course, you will also have to fix another branch of your conditional.

, - , - .

+2

, , ?

  • ,
  • ,

, SQL-.

SELECT SUM(amount) FROM transactions;

+2

Source: https://habr.com/ru/post/1780564/


All Articles