Add values returned from while

0

I have a table that has the value column, I query those values as follows

$sql2 = 'SELECT * FROM comisao_trabalho WHERE idJob="10" && pagoA="Dalton" ORDER BY id ASC';
$buscar = $conexao->prepare($sql2); 
$buscar->execute();

$retorno = array();
$retorno['dados'] = '';
$retorno['qtd'] = $buscar->rowCount();

if($retorno['qtd'] > 0):

    while($conteudo = $buscar->fetchObject()){
        $retorno['dados'] = $conteudo->valor;
    }                                            

    echo json_encode($retorno);
endif;

The values are in this format: U $ 2,500.00

    
asked by anonymous 25.09.2017 / 21:51

2 answers

2

You can add with an auxiliary variable within the while:

$aux = 0;
while($conteudo = $buscar->fetchObject()){
    $aux += $conteudo->valor;
}
$retorno['dados'] = $aux;

And at the end of the while iteration, you would have the total value saved in $ aux

    
25.09.2017 / 22:49
4

You can do the VALUE_TOTAL directly via SQL and by naming a field, in this case your query would look like this:

SELECT id, idJob, pagoA, SUM(valor) AS valorTotal 
FROM comisao_trabalho 
WHERE idJob="10" && pagoA="Dalton" 
ORDER BY id ASC

It is not recommended that you use SELECT * FROM, for testing purposes only. The AS field assigns a nickname to the table, you can put any name, that is to say that the sum of the values of the valor column will be placed in an imaginary column called valorTotal .

In PHP you would have a column called TotalTable that returns the sum of the values.

Eg: $retorno['dados'] = $conteudo->valorTotal;

  

It is important to remember that in this example you will have the return of a row, that is, a record with the total value of the others that fell in the WHERE clause .

Learn more

25.09.2017 / 22:02