I need to add some fields to a table. I have the transaction id and I need to sum all the amount
fields with the id 224, all with 222.
You can do this by just using a select in the database, making your life easier. In your case the select will look like this:
select sum(amount) as 'amount' from 'tb_customer_credit' where customer_id = 224
Regarding the above line of code, you only need to replace 224 with the name of the variable that will be used by your application to send the ID.
You could also get the highest value, among other things using just select, thus reducing the amount of things in php and decreasing the response time of your site.
You can do this by using the SUM
function and grouping the records by the field you want with GROUP BY
. Example:
SELECT 'customer_id', SUM('amount') AS 'amount'
FROM 'tb_customer_credit'
GROUP BY 'customer_id';
This will have the sum of all records. If you need the sum of just one record, you can do as @BernardoKowacic did, using WHERE
.