Sharoon Ck
Sharoon Ck

Reputation: 788

how to insert a value to sql database by summing last row value and the inserting value

my table like this

id  debt   balance
1   1000   
2   500    
3   600   

i want table like this when i insert new debt value

id  debt   balance
1   1000   1000
2   500    1500
3   600    2100

eg when i add debt value 1000 need to update balance as sum of the value

id  debt   balance
1   1000   1000
2   500    1500
3   600    2100
4   1000   3100

Upvotes: 1

Views: 262

Answers (2)

Fahmi
Fahmi

Reputation: 37473

You can try below

update tablename
set balance=debt+(select balance from tablename order by id desc limit 1)

Upvotes: 0

ashir haroon
ashir haroon

Reputation: 243

SELECT balance from table order by desc limit 1

after fetching last balance add it to the current dept value

$balance = $row['balance'];
$dept = $_POST['dept'];
$new_val = $dept+$balance;

add this new_val to the new balance field

INSERT INTO table (debt, balance) VALUES ('$dept', '$new_val');

Upvotes: 2

Related Questions