Adding numbers from a MySQL column using PHP

3

I have several results in the MySQL database, I want to get the results and add all the numbers of a column in PHP. How do I?

    
asked by anonymous 20.06.2015 / 19:35

2 answers

8

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

Once you've done this, simply run a query using the SUM () of MySQL:

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

And to use the query result:

$resultado = $mysqli->fetch_assoc();
    
20.06.2015 / 19:59
0

You're apparently using PDO , so here's an example:

$STH_SELECT = $dbh->query("SELECT sum(coluna_pra_somar) FROM catalogo_comment WHERE cm_item = '2'");
$totalSoma = $STH_SELECT->fetchColumn();
    
20.06.2015 / 20:19