Sum of table fields with PHP and Codeigniter

3

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.

    
asked by anonymous 23.03.2016 / 12:19

2 answers

2

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.

    
23.03.2016 / 12:27
3

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';

SQLFiddle

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 .

    
23.03.2016 / 12:42