How to store the sum of the values that are entered in mysql and php

0

Good day! I commented: I have a table called "products" and I want to add the values that are entered in "$ amount" in a column that is called "$ total". This to keep track of the available stock. I have the following code:

function agregar_total($id_producto,$nombre,$cantidad){
global $con;    
$update=mysqli_query($con,"update productos set total=total+'$cantidad' where id_producto='$id_producto'"); 

For some reason you are updating all the data in the "total" column and not just the last row. In addition to this, it performs the addition in reverse order, that is, it adds from greater to lesser id. So the first product that you enter is with more stock than the last one that I have entered. I hope you can help me out. Anything I have at your disposal if I have missed some important information.

    
asked by adriancasanova 30.07.2018 в 14:41
source

1 answer

0

To take only the last row and with normal or ascending order, the query would be:

$update=mysqli_query($con,"update productos set total=total+'$cantidad' 
where id_producto='$id_producto' order by id_producto asc limit 1");

This orders you from lowest to highest by id and you only take the first one with the limit .

    
answered by 30.07.2018 / 16:29
source