I am making a personal finance program in PHP and I'm getting stuck on what should be an easy to accomplish task - balancing the account.
Transactions are stored in MySQL, each has a type - 1 for withdraw, 2 for deposit. Below is my PHP for balancing the account, not getting anywhere near the correct 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 =开发者_Python百科 $balanceEntry['amount'];
if ($balanceEntryType == "1") {
$accountBalance = $startingBalance - $balanceEntryAmount;
} else if ($balanceEntryType == "2") {
$accountBalance = $startingBalance + $balanceEntryAmount;
}
}
Any ideas? Thanks
$accountBalance = $startingBalance - $balanceEntryAmount;
This means every time you hit this line you're setting the current balance to the original balance minus the entry amount. You probably want to assign, before your while loop:
# or just rename $startingBalance to $accountBalance
$accountBalance = $startingBalance;
and then in your while loop
$accountBalance = $accountBalance - $balanceEntryAmount;
Of course you'd have to fix the other branch of your conditional, too.
Next time you have an error in something like this try outputting the current value of the each calculation in a log file - you would have figured this out very quickly.
Rather than store a "transaction type" column, why not just store a signed transaction value?
- positive if it's a deposit
- negative if it's a withdrawal
This way, you can get the account balance with a simple sql query.
SELECT SUM(amount) FROM transactions;
精彩评论