php - 支票簿余额 PHP

标签 php mysql

我正在用 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;

当然,您还必须修复条件的其他分支。

下次您遇到此类错误时,请尝试在日志文件中输出每个计算的当前值 - 您会很快发现这一点。

关于php - 支票簿余额 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4456238/

相关文章:

php - 如何在同一选择中使用 3 AND?

mysql - 将数组保存在 Rails 4 中

php - 在if条件php中使用for循环计数器

mysql - 如何在 Angular JS 中从数据库获取信息到 div 或表单字段?

mysql - SQL 不同的多个查询合并

javascript - Jplayer - 从 Mysql 结果创建动态播放列表

php - 如何集成 HTML Purifier 来过滤用户提交的数据?

php - Laravel 邮件不通过队列发送

php - 当选择下拉列表更改时重新显示 php mysql 表

php - 查询期间之间的日期