Count Database result [closed]

0

Hello. Good night.

I have a question

I want to sum all the values of the field valor_reais of my table

forexample

  • id1=150
  • id2=100
  • id3=100

Iwanttheobviousresult,350

I'vetriedsomethinglike:

$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 is returning 450

    
asked by anonymous 08.04.2018 / 22:47

2 answers

2

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

$quantidade * $valor_final
What ... guess what? It is 450 , result of (3 * 150)

An alternative to add would simply be:

SELECT SUM(campo) FROM tabela

Or make a loop in the results, effectively making a sum:

$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)

    
08.04.2018 / 22:51
0

Only use the sql aggregate function: SUM

$stmt = $pdo->prepare("SELECT SUM(valor_reais) as total FROM tabela");
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_OBJ);
echo $row->total;
    
08.04.2018 / 23:10