How to sum a column of a database using PDO

1

Good evening, everyone. I have little programming experience. I apologize if I am not very clear on the question.

I have a MySQL database (phpmyadmin) with a table named "my_table" having one of the fields named "value". I need to add the "value" field of all table rows.

To count how much data worked, how much I used the following snippet:

$select = $pdo->query("SELECT * FROM minha_tabela")->fetchAll();

// atribuindo a quantidade de linhas retornadas
$count = count($select);

// imprimindo o resultado
print $count;

Now I need to do the sum and I do not know how to write the program. I am using PDO programming. Many thanks.

    
asked by anonymous 15.11.2016 / 02:06

2 answers

2

Use the following SQL query:

SELECT SUM(valor) AS total FROM minha_tabela

See more details on how to use SUM here .

Then, in PDO you do this:

$soma = $pdo->query("SELECT SUM(valor) AS total FROM minha_tabela")->fetchColumn();

// Imprimindo o resultado.
print $soma;
    
15.11.2016 / 02:22
1
$stmt = new PDO("mysql:host={$servername};dbname={$dbname}",$username, $password);
$stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$soma = $stmt->query("SELECT SUM(valor) as total FROM nome_tabela")->fetchColumn();
//imprime com as pontuação e virgula
print number_format($soma, 2, ",",".");
    
01.10.2017 / 23:57