Adding numbers from a MySQL column using PHP

Question:

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

Answer:

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

Once that's done, just run a query using MySQL's SUM() function:

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

And to use the query result:

$resultado = $mysqli->fetch_assoc();
Scroll to Top