I have been trying to figure out a weird issue with signed integers and PHP in a finance app I am working on. Each transaction’s amount is a signed integer, I balance the account using SUM() and have a function that should output each entry with a running balance, ordered by the row’s id and date in descending order.
Everything appeared to be working fine until the account balance went below 0 (-6.20 or so). When a deposit was entered, instead of simply returning to a positive number, the running total output 1.00 and the running total of nearly every transaction prior to it read as a negative – except for perhaps the ones that were either near or below $0. Quite puzzled.. here is the function (part of a class):
public function fetchTransactions($limit = null) {
global $db;
$this->balanceAccount(); //Calls upon another function to return the balance
$runningTotal = $this->accountBalance;
$prevAmount = 0;
if (isset($limit)) {
$sql = "SELECT amount, payee, cat, date FROM transactions ORDER BY date DESC, id DESC LIMIT $limit";
} else {
$sql = "SELECT amount, payee, cat, date FROM transactions ORDER BY date DESC, id DESC";
}
$fetchTransactionsSQL = $db->query($sql);
while ($transactionDetails = $fetchTransactionsSQL->fetch()) {
$date = date("m/d", strtotime($transactionDetails['date']));
$payee = stripslashes($transactionDetails['payee']);
$category = $transactionDetails['cat'];
$amount = $transactionDetails['amount'];
$runningTotal -= $prevAmount; //I have also tried addition here
$prevAmount = $amount;
$amountOutput = (strpos($amount, '-') === true ? '-' . money_format("%n", $amount) : money_format("%n", $amount));
$runningTotalOutput = money_format("%n", $runningTotal);
echo "
<tr>
<td>$date</td>
<td><strong>$payee</strong></td>
<td>$category</td>
<td>$amountOutput</td>
<td>$runningTotalOutput</td>
</tr>
";
}
}
Any help would be greatly appreciated. Thanks!
EDIT = Further explanation
To clear up some confusion. The entries are being pulled from the database in descending order, where the last transaction is at the end of the MySQL table but the first one displayed on the page. I start $prevAmount at 0 and then set it to the current transaction’s amount during the loop. $runningTotal starts as the overall account balance and the running balance is obtained by subtracting the previous transaction’s amount ($prevAmount) from $runningTotal during the loop. If anyone can suggest an easier way to accomplish this I’m all ears — it worked great until the account balance fell below 0.
A simple case of needing to look elsewhere in my code for the problem. For whatever reason, I had used
number_format()on both the Starting Balance and Account Balance function’s output. Apparently this gets in the way of mathematical operations, everything works as it should after removing this from those functions. Boo for bad code, hooray for figuring it out!