Count Database output

Asked

Viewed 56 times

0

hello. good night.

I have a question

I want to add up all the field values valor_reais of my table

exemplo

for example

  • id 1 = 150
  • id 2 = 100
  • id 3 = 100

I want the obvious result, 350

I’ve tried something like:

$buscar = $pdo->prepare("SELECT * FROM tabela");
$buscar->execute();
$valor = $buscar->fetch(PDO::FETCH_OBJ);
$quantidade = $buscar->rowCount();
$valor_final = $valor->valor_reais;
echo $quantidade * $valor_final;

but it’s returning 450

  • 1

    if you want to add, why are you multiplying by the amount???

2 answers

2


The "obvious result" is correct. You are displaying:

$quantidade * $valor_final

Which... guess what. Yeah 450, result of (3 * 150)

An alternative to add up would simply be:

SELECT SUM(campo) FROM tabela

Or make a loop in the results, effectively summing up:

$buscar = $pdo->prepare("SELECT * FROM tabela");
$buscar->execute();

$valor_final = 0; // Iniciamos com zero                                  
while ($valor = $buscar->fetch(PDO::FETCH_OBJ)) { // percorremos cada linha
  $valor_final += $valor->valor_reais;            // e adicionamos ao valor_final
}
echo $valor_final;

(adjust the variables to your actual case)

0

Only use the added sql function: SUM

$stmt = $pdo->prepare("SELECT SUM(valor_reais) as total FROM tabela");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
echo $row->total;
  • How do I print this?

  • I edited the answer for you to see.

Browser other questions tagged

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