Add Mysql + PHP fields

Asked

Viewed 1,558 times

1

I have the code below where I need to add the value of a column (Mysql) and the result of this sum, subtract by any value, example: 5000 and the result of this operation is passed to the PHP page.

My code:

<?php

$opcoes2 = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
$conexao2 = new PDO("mysql:host=".SERVER."; dbname=".DBNAME, USER, PASSWORD,          $opcoes2);

$sql2  = "SELECT SUM(valor_boleto) - 5000 FROM boleto";
$stm2 = $conexao2->prepare($sql2);
$stm2->execute();

while($row2 = $stm2->fetch())  {
$soma = $row2['sum(valor_boleto)'];
 }  

?>

HTML:

<html>
  <body>
   A Soma dos Números do Banco de Dados foi <?=$soma?>.

    <div id="chart_div"></div>
   </body>
 </html>

The error generated is:

Notice: Undefined index: sum(valor_boleto) in C: xampp htdocs grafico.php on line 77

The select is OK, I see console returns the right value.

If my column "valor_boleto" there are 3 fields of 5000, would add up 15000 and subtracting by 5000, should return a "echo" of 10000.

Grateful who can help.

1 answer

4


Groups the operation and gives an alias that resolves.

SELECT (SUM(valor_boleto)-5000) AS total FROM boleto

Ai la no php picks up the total like this:

$soma = $row2['total'];
  • Straight shot huh?? It worked! Thanks Neuber, hugs.

Browser other questions tagged

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