如何从数据库中的值总和中减去值

时间:2019-03-27 16:43:15

标签: php html mysql

我应该从数据库中的值的总和中减去给定的值!

例如:用户“ John”用2次100 $和50 $填充了他的帐户,在他的帐户中总计150 $ 当他以50美元的价格购买水货时,我们应该减去他帐户中的总金额! 并且应该更新总金额。

以下代码可显示其帐户中的总金额:

 <?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'] . "";
    ?>

表格:付款

  ID      username    payment_amount    Status  
+-------+-------------+-------------+-----------+
|   1   |  John       |     100     | Complete  |
+-------+-------------+-------------+-----------+
|   2   |  John       |     50      | Complete  |
+-------+-------------+-------------+-----------+
|   3   |  Alex       |     100     | Complete  |
+-------+-------------+-------------+-----------+

2 个答案:

答案 0 :(得分:0)

使用天平时,请勿这样做。

最好的方法是创建一个像这样的新表。

ID | userId |平衡

然后,每次付款时,您只使用用户余额中的+ $ amount更新数据库,并且,如果他花了钱,则只需在UPDATE中执行-$ amount。

示例:

tbl_user

ID |名称|电子邮件

1..alex ... blabla@test.com


tbl_balance

ID | userId |平衡

1 .... 1 ..... 100

答案 1 :(得分:0)

是的,我可以向您展示我将如何执行此操作,但它不会100%充满,而是向您显示其工作原理。

/////PAYMENT PAGE/////

<?php 
/////Get the ID of user using his session username and after all you query your     user table WHERE username = $_SESSION["username"] and then you take the ID 
////And you save the id of user in a variable 
$getId = $row["id"];

/////Get the total balance of user right now using his id and save in variable
$getAmountNow = $row["balance"];
?>

<form action="myscript.php" method="get"> 
How much you want to pay <input type="text" name="amountPaid"><br>
<input type="hidden" name="<?php echo $getId; ?>"><br>
<input type="hidden" name="<?php echo $getAmountNow; ?>"><br>
<input type="submit" value="Submit">
</form> 
/////PAYMENT PAGE/////



/////myscript.php/////

$idUser = htmlspecialchars($_POST["id"]);
$amountNowUser = htmlspecialchars($_POST["balance"]);
$amountPaid = htmlspecialchars($_POST["amountPaid"]);

////If this is a spent
$newAmount = $amountNowUser - $amountPaid;

////If this is a buy
$newAmount = $amountNowUser + $amountPaid;

// prepare and bind$stmt = $conn->prepare("UPDATE tbl_balance SET balance=? WHERE     idUser=?");
$stmt->bind_param("ss", $newAmount, $idUser);
$stmt->execute();


/////myscript.php/////