I'm developing a personal finance control system and I want to create a balance column similar to a Bank Statement. My data is stored in a MySQL database with the following structure:
| ID | Type | Date | Description | Amount |
|---|---|---|---|---|
| 01 | D | 01/02/2024 | Transaction 1 | 150,00 |
| 02 | D | 03/02/2024 | Transaction 2 | 250,00 |
| 03 | D | 05/02/2024 | Transaction 3 | 50,00 |
| 04 | C | 06/02/2024 | Transaction 4 | 980,00 |
I need to create a column that stores the previous balance from a query. Each row will update this column with the current balance. Here's an example (assuming that the previous balance is 250.00):
| ID | Type | Date | Description | Amount | Balance |
|---|---|---|---|---|---|
| 01 | D | 01/02/2024 | Transação 1 | -150,00 | 100,00 |
| 02 | D | 03/02/2024 | Transação 2 | -250,00 | -150,00 |
| 03 | D | 05/02/2024 | Transação 3 | -50,00 | -200,00 |
| 04 | C | 06/02/2024 | Transação 4 | 980,00 | 780,00 |
That's what I'm doing in PHP:
$transacoes = '
<table id="tabAccountDetails" class="table lms_table_active" style="width:100%">
<thead>
<tr>
<th scope="col" hidden>#</th>
<th scope="col">Date</th>
<th scope="col">Description</th>
<th scope="col">Amount</th>
<th scope="col">Balance</th>
</tr>
</thead>
<tbody>';
$earlierBalance= 0;
$saldo = 0;
while ($reg = mysqli_fetch_assoc($res)) {
if ($saldoAnterior == 0) {
$earlierBalance = $reg["EarlierBalance"];
$balance = $reg["TransactionAmount"] + $earlierBalance ;
} else {
$balance = $reg["TransactionAmount"] + $balance;
}
$transactionId = $reg["TransactionId"];
$account = $reg["AccountName"];
$description = $reg["TransactionDescription"];
$date = $reg["TransactionDate"];
$amount = $reg["TransactionAmount"];
$transacoes .= '
<tr>
<td>' . $transactionId . '</td>
<th scope="row">' . $date . '</th>
<td>' . $description . '</td>
<td>' . number_format($ammount, 2, ",", ".") . '</td>
<td>' . number_format($saldo, 2, ",", ".") . '</td>
</tr>';
}
$transacoes .= '
</tbody>
</table>';
echo $transacoes;
For some reason, it is not correctly updating for all rows returned from the database. This is the query I'm using to select the transactions:
SELECT t.TransactionId,
t.AccountId,
a.AccountName,
DATE_FORMAT(t.TransactionDate, '%d/%m/%Y') TransactionDate,
t.TransactionDescription,
t.TransactionType,
t.TransactionAmount,
(select SUM(if(TransactionType = 'C', TransactionAmount, TransactionAmount*-1))
FROM tbtransactions
WHERE UserId = $userId AND AccountId = $idConta AND TransactionDate < '$initialDate') EarlierBalance
FROM tbtransactions t
INNER JOIN tbaccount a ON a.AccountId = t.AccountId
WHERE t.UserId = $userId AND t.TransactionDate BETWEEN '$initialDate' AND '$finalDate'
ORDER BY t.TransactionDate
Can somebody give me any north or help regarding the best way to do it?