2016-11-20 59 views
0

我想用mysql數據庫在php中編碼,並且我想用儲值和新的輸入值來計算餘額。例如我有數據庫是這樣的: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形式inputed這樣新值:

借記= 30000
信用= 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腳本?謝謝。

回答

0

如果表中沒有行,則初始化爲0。之後得到表中的最後一行,並從該行獲取old_balance。只需將該腳本放在$ credit = ....行後面即可。如果沒有行,您將從最後一行獲得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"]; 
} 
+0

收到錯誤:)mysqli_num_rows(預計參數1被mysqli_result,在balance.php定的boolean – RA121514

+0

改變你的表名或列名從「平衡」到任何其他名稱,並嘗試在執行選擇查詢phpmyadmin檢查它是否返回任何數據。 –

+0

當您的查詢未成功執行時,會出現此錯誤。所以按照上面的評論做 –