Adding numbers from a Mysql column using PHP

Asked

Viewed 4,434 times

3

I have several results in the Mysql database, I want to take the results and sum all the numbers in a column, in PHP. How do I?

  • 1

    Could you elaborate a little more on your question? What have you got so far?

2 answers

8

First you need to connect to your database through the extension MySQLi, documentation here.

Once done, just run a query using the function SUM() mysql:

$mysqli = new mysqli('localhost', 'usuario', 'senha', 'banco');
$mysqli->query('SELECT SUM(coluna) FROM tabela');

And to use the result of the consultation:

$resultado = $mysqli->fetch_assoc();
  • You do not understand, I want to add the numbers within a column and not display the amount of registrations,

  • 1

    I understood perfectly, the function SUM() sum all numbers of a particular column of your table. @Lenosousa

  • Okay, but how to use this function? Could you demonstrate some example? based on the code I already have.. $comment = $dbh->prepare("SELECT * FROM catalogo_comment WHERE cm_item = '2'"); $comment->execute(); while ( $cm = $comment->fetch( PDO::FETCH_OBJ) ) { ; };

  • The ideal is to add this information to your question. But basically instead of SELECT *, you replace by SELECT SUM(nome_da_coluna) FROM...

0

Apparently you’re using PDO, then follow an example:

$STH_SELECT = $dbh->query("SELECT sum(coluna_pra_somar) FROM catalogo_comment WHERE cm_item = '2'");
$totalSoma = $STH_SELECT->fetchColumn();
  • The following error appeared, "Fatal error: Call to a Member Function fetchColumn() on a non-object in /home/..."

  • @Lenosousa Show me which query you executed

Browser other questions tagged

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