Running Balance with PHP and MySQL
I am working on a simple fina开发者_运维百科nce tracker and appear to be stuck trying to figure out what should be a simple task using PHP and MySQL - displaying a running financial balance.
There are two MySQL tables, one with the starting balance for each account and a second with the individual transactions. For the purpose of development, I am only working with one account. What I am trying to do is iterate through the transactions and display a running total, subtracting from the starting balance if it is a withdraw or adding if it is a deposit. The amount
column for each transaction is negatively signed for withdraws and positively for deposits.
Here is what I have tried without any luck:
<?php
$getTransactions = $db->query("SELECT * FROM transactions ORDER BY date, id");
//Get the starting balance
$getStartingBalance = $db->query("SELECT amount FROM startingBalance WHERE id = 1");
$startingBalance = $getStartingBalance->fetch();
//Start off with Running Total same as Starting Balance
$runningTotal= $startingBalance['amount'];
//Iterate through transactions
while ($transaction = $getTransactions->fetch()) {
$amount = $transaction['amount'];
if ($amount < 0) {
$runningTotal = $runningTotal - $amount;
} else {
$runningTotal = $runningTotal + $amount;
}
}
?>
The above will perform addition even if the number is negative. How would I accomplish this with signed numbers? In the past, I was using an integer to differentiate between deposits and withdraws (1 for deposit, 2 for withdraw) but it was suggested that signed values would be the better route.
Thanks for any help
A negative negative is a positive! For example 3 - (-1) == 4
As your transactions are signed, you don't need to selectively add or subtract. You can skip:
if ($amount < 0) {
$runningTotal = $runningTotal - $amount;
} else {
$runningTotal = $runningTotal + $amount;
}
And replace it with just
$runningTotal = $runningTotal + $amount;
You've got a sign error.
if ($amount is less than zero) {
subtract from total
} else {
add to total
}
Remember basic math: negative number minus a negative number is actually an addition. Since you've got signed numbers, there's no need for the <0
check, just add all the numbers:
$total = $total + $amount;
if $amount is negative, it'll naturally become a subtraction.
精彩评论