我正在用PHP开发个人理财程序,但我陷入了应该很容易完成的任务-平衡帐户.
事务存储在MySQL中,每个事务都有一个类型-1用于提款,2用于存款.下面是我的PHP,用于平衡帐户,但收不到正确的金额.
//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;
}
}
有任何想法吗?谢谢
解决方法:
$accountBalance = $startingBalance-$balanceEntryAmount;
这意味着,每次点击此行,您都将当前余额设置为原始余额减去输入金额.您可能要在while循环之前分配:
# or just rename $startingBalance to $accountBalance
$accountBalance = $startingBalance;
然后在你的while循环中
$accountBalance = $accountBalance - $balanceEntryAmount;
当然,您也必须修复条件语句的另一个分支.
下次如果您遇到类似这样的错误,请尝试将每个计算的当前值输出到日志文件中-您会很快发现这一点.
标签:mysql,php
来源: https://codeday.me/bug/20191105/1996260.html