PHP - 使用以前的值计算余额

时间:2016-11-20 10:40:17

标签: php

我正在尝试使用mysql数据库在php中创建代码,我想用存储的值和新的输入值来计算余额。例如,我有这样的数据库:

id  |  debit  | credit | balance
----+---------+--------+--------
 1  |   70000 |      0 |  70000
 2  |       0 |  44000 |  26000
 3  |   45000 |  15000 |  56000
 4  |       0 |  32000 |  24000
 5  |       0 |  10000 |  14000
 6  |   28000 |      0 |  42000

公式为balance = old_balance + new_inputed_debit - new_inputed_credit
所以如果我以html形式输入这样的新值:

  

debit = 30000
  credit = 5000

所以当我点击输入按钮balance = 42000 + 30000 - 5000时,脚本将对此进行求和 数据库将变成这样:

id  |  debit  | credit | balance
----+---------+--------+--------
 1  |   70000 |      0 |  70000
 2  |       0 |  44000 |  26000
 3  |   45000 |  15000 |  56000
 4  |       0 |  32000 |  24000
 5  |       0 |  10000 |  14000
 6  |   28000 |      0 |  42000
 7  |   30000 |   5000 |  67000 <-- New Submited Value

这是我的php脚本:

<?php
    require('db2.php');
    // If form submitted, insert values into the database.
    if(isset($_POST['submit'])) {
        $debit = mysqli_real_escape_string($con,$_POST['debit']);
        $credit = mysqli_real_escape_string($con,$_POST['credit']);
        $balance = //old_balance + new_inputed_debit - new_inputed_credit
        $query = "INSERT into `balance` (debit, credit, balance,) VALUES ('$debit','$credit', '$balance')";
        if(mysqli_query($con,$query)){
            echo "<div class='form'><h3>Inputed Success</h3><br/><a href='Input.php'>Input again</a></div> or <a href='index.php'>back</a>";
        }else{
        }
    }
?>

这是我的HTML代码:

<form name="input_data" action="" method="post"><br />
<label style="font-size:16px;">Debit :</label>
<input type="text" name="debit" placeholder="Ex: 90000" style="margin-left:3px; width:80% !important;" required /><br />
<label style="font-size:16px;">Credit :</label>
<input type="text" name="credit" placeholder="Ex: 90000" style="margin-left:3px; width:80% !important;" required /><br />
<span style="float:right;"><input type="reset" name="reset" value="RESET" style="margin-right:8px;" /> <input type="submit" name="submit" value="INPUT" style="margin-right:8px;" /></span>
</form>

有人可以帮我创建php脚本吗?感谢。

2 个答案:

答案 0 :(得分:0)

如果表中没有行,则将余额初始化为0。之后从表中获取最后一行并从该行获取old_balance。只需将此脚本放在$ credit = .... line之后。您将从最后一行获得old_balance,如果没有行,则返回0。

$old_balance = 0;
$sql = "select max(id), balance from balance_table";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) == 1){
    $row = mysqli_fetch_assoc($result);
    $old_balance = $row["balance"];
}

答案 1 :(得分:0)

也许这对你有用:)

$old_balance = 0;
$sql = "select max(id), balance from balance";
$result = mysqli_query($con,$sql);
if(mysqli_num_rows($result) == 1){
    $row = mysqli_fetch_assoc($result);
    $old_balance = $row["balance"];
}