John Davidson

mysql - How to get real time balance in php

0 comments
Message:


For example I have a variable $opening_balance = 5000; Now more transactions are taking place with debit and credit and I want to fetch data from database and want to print real time balance at the end of each row. Following is is an example what I want exactly in my results.


----------------------------------------------------
| Sr No. | Description | Debit | Credit | Balance |
----------------------------------------------------
| 1. | Debit | 500 | - | 4500 |
| 1. | Credit | - | 1000 | 5500 |
| 1. | Debit | 200 | - | 5300 |
----------------------------------------------------

Following is my code: -


$query = mysqli_query($conn, "SELECT * FROM patty_cash WHERE month(date) = '11' AND year(date) = '2020' ");
while($row = mysqli_fetch_assoc($query))
{
extract($row);
$newBalance = $opening_balance + $credit - $debit;
echo "<tr>
<td>$sr_no</td>
<td>$description</td>
<td>$debit</td>
<td>$credit</td>
<td>$newBalance</td>
</tr>";
}

But I am not getting accurate balance. Please suggest what to do to get accurate balance.



My Answer:
You need to update the $opening_balance variable inside the loop to keep track of the real-time balance. Here is the updated code:

php
$query = mysqli_query($conn, "SELECT * FROM patty_cash WHERE month(date) = '11' AND year(date) = '2020'");
$opening_balance = 5000; // Initial opening balance
while($row = mysqli_fetch_assoc($query))
{
extract($row);
$newBalance = $opening_balance + $credit - $debit;
echo "
$sr_no
$description
$debit
$credit
$newBalance
";
$opening_balance = $newBalance; // Update opening balance for next iteration
}


By updating the $opening_balance variable inside the loop, you will be able to calculate the real-time balance accurately for each row.

Rate this post

5 of 5 based on 9324 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us