Sum of table fields with PHP and Codeigniter

Asked

Viewed 916 times

3

I need to add some fields from a table. I have the transaction id and need to add all fields amount with id 224, all with 222.

inserir a descrição da imagem aqui

  • You need to add all the amount that has the same customer_id?

  • Yes, I think it would be more or less like the answer below.

2 answers

3

You can do this using the function SUM 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

So you have the sum of all the records. If you need the sum of only one record, you can do it the way @Bernardokowacic did, using the WHERE.

  • 1

    It would only be 1 even, I managed to do with the code of @Bernardokowacic, this id I get from the user cookie.

2


You can do this using only a select in the database, making your life easier. In your case the select will be as follows:

select sum(amount) as 'amount' from `tb_customer_credit` where customer_id = 224

Referring to the above line of code, you will only need to replace the value 224 by the name of the variable that will be used by your application to send the ID.

You could also get the most value, among other things using select only, thus decreasing the amount of things in php and decreasing your site’s response time.

  • 1

    To do in Code Igniter, you must create a new function in your Model class (where you make the selects in BD) and paste this code there.

  • Perfect, I just had to exchange the 224 for the id I’m pulling and it worked perfectly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.