php - PHP - 仅在 IF 语句更改时显示计算
问题描述
这是我的代码:
<table class="table table-bordered">
<thead>
<tr>
<th>Sr#</th>
<th>Description</th>
<th>Sale</th>
<th>Expense</th>
</tr>
</thead>
<tbody>
<?php
$fetch_record = "SELECT * FROM `transactions` JOIN `users` ON `transactions`.`user_id`=`users`.`user_id` WHERE `users`.`user_id`='$user_id'";
$fetch_record_r = mysqli_query($con, $fetch_record);
$record_found = mysqli_num_rows($fetch_record_r);
if ($record_found > 0) {
$sr = 1;
$net_total = 0;
while($records = mysqli_fetch_assoc($fetch_record_r)){
if ($records['type'] == 1) {
$net_total = $net_total + $records['sale'];
}else if($records['type'] == 2){
$net_total = $net_total - $records['expense'];
}
?>
<tr>
<td><?php echo $sr++; ?></td>
<td style="text-transform: capitalize;"><?php echo $records['description']; ?></td>
<td><?php echo $records['sale'];?></td>
<td><?php echo $records['expense'];?></td>
</tr>
<?php
if (($sr % 2)) { // skip even members
?>
<tr>
<td colspan="2"></td>
<td colspan="2" class="label-info text-center" style="color: #fff;">Total Balance: <?php echo $net_total; ?></td>
</tr>
<?php
}
?>
<?php
}
?>
<tr>
<td colspan="4" class="label-info text-center" style="color: #fff;">Total: <?php echo $net_total; ?></td>
</tr>
<?php
}else{
echo "<h1 class='text-center text-danger'>No Record Found</h1>";
}
?>
</tbody>
</table>
数据来自数据库,但不是计算。我希望当交易类型从销售变为费用时,应该计算所有与销售相关的交易,反之亦然。就像资产负债表一样。我知道我写了一个错误的逻辑。但我无法解决这个逻辑。通过查看图像,您可以更清楚地理解我的问题。销售费用计算器示例
解决方案
当收入中的条目数超过一个时,您似乎正在尝试获得总价值,对吗?
如果是这样,请考虑采用以下方法来获得总数。
SELECT SUM(**column_name**)
FROM **table_name**
WHERE **condition**;
您可以将结果分配给变量,并使用 if 语句填充相同的结果。
您可以使用 if 语句检查返回的行数是否大于 1,执行上述 SQL 语句,并填充计算/结果。
推荐阅读
- java - 如何在 Docker for Windows 上运行 selenium 测试
- project-reactor - 规避默认请求大小的负面影响
- javascript - 带有输入操作的网络通知
- javascript - 如何制作可被多个页面访问的 javascript 变量?
- arrays - Postgres:“无法在对象上调用 json_populate_recordset”错误
- docker - 在 docker-compose 中重用 docker 镜像
- html - HTML & CSS - 将对象移动到特定位置
- r - R Markdown - Highcharter - 可见时动画图表,而不是页面加载?
- javascript - 从新选项卡捕获事件提交
- javascript - 如何将 2 个数组合并为一个数组