php - How to substract value from sum of values in Database
问题描述
I should substract given value from sum of values in Database!
For example: User "John" filled his account 2 time 100$ and 50$, Total in his account 150$ When he buy smth for 50$ We should substract from total money in his account! and total money should be updated.
Here code to display total money in his account:
<?php
session_start();
$sql = "SELECT sum(payment_amount) as 'payment' from payments
WHERE username= '" . $_SESSION['username'] . "' ";
$result = $db->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "" . $row['payment'] . "";
?>
table: Payments
ID username payment_amount Status
+-------+-------------+-------------+-----------+
| 1 | John | 100 | Complete |
+-------+-------------+-------------+-----------+
| 2 | John | 50 | Complete |
+-------+-------------+-------------+-----------+
| 3 | Alex | 100 | Complete |
+-------+-------------+-------------+-----------+
解决方案
当您使用 balance 时,您不应该这样做。
最好的方法是像这样创建一个新表。
身份证 | 用户名 | 平衡
然后每次付款,您只需在用户余额中使用 +$amount 更新数据库,而且,如果他花钱,您只需在更新中执行 -$amount。
例子:
tbl_user
身份证 | 姓名 | 电子邮件
1..亚历克斯...blabla@test.com
tbl_balance:
身份证 | 用户名 | 平衡
1....1........100
推荐阅读
- android - 在 Android 中正确模拟和测试交互器类
- android - 从 Kotlin 中的 AsyncTask 返回一个值
- javascript - 根据id转换json数组
- php - URL PHP 基本身份验证这是一个安全问题吗?
- javascript - 如何修复 CodeMirror 中的输入问题
- php - 安装 Phalcon 3.4.3 并获得 4.0 Alpha
- javascript - 来自数组的 RxJS - 观察数组并在更改时写入控制台?
- java - 如何将负数格式化为括号?
- .net-core - 将 Microsoft nuget 与较低的 dotnet 核心版本相结合
- image-processing - 图像分割中的高阶势解释