![](/img/trans.png)
[英]What's the most efficient way to calculate a running total/balance when using pagination (PHP, MySQL)
[英]Running Balance with PHP and MySQL
我正在研究一個簡單的財務跟蹤器,並且似乎陷入困境,試圖弄清楚使用PHP和MySQL應該是一個簡單的任務 - 顯示正在運行的財務平衡。
有兩個MySQL表,一個具有每個帳戶的起始余額,另一個具有單個事務。 出於開發目的,我只使用一個帳戶。 我想要做的是迭代交易並顯示一個運行總計,如果是提款則從起始余額中減去,如果是存款則從中減去。 每筆交易的amount
列對提款有負面簽名,對存款有正面評價。
這是我沒有運氣的嘗試:
<?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;
}
}
?>
即使數字為負,上述內容也會增加。 如何使用簽名號碼完成此操作? 在過去,我使用整數來區分存款和取款(1存款,2存款取款),但有人建議簽署的價值是更好的路線。
謝謝你的幫助
負面消極是積極的! 例如3 - (-1) == 4
在您的交易簽名時,您無需有選擇地添加或減去。 你可以跳過:
if ($amount < 0) {
$runningTotal = $runningTotal - $amount;
} else {
$runningTotal = $runningTotal + $amount;
}
並用它替換它
$runningTotal = $runningTotal + $amount;
你有一個標志錯誤。
if ($amount is less than zero) {
subtract from total
} else {
add to total
}
記住基本數學:負數減去負數實際上是一個補充。 由於你有簽名號碼,所以不需要<0
檢查,只需添加所有數字:
$total = $total + $amount;
如果$ amount為負數,它自然會變成減法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.