Sum all records of an INT field in PHP and display it

Asked

Viewed 34 times

-2

Well, basically I need to add up all my records from my field valor of my table contas that’s like INT in the bank, the problem is that the result is giving "0,01", where I’m going wrong?

inserir a descrição da imagem aqui

Divided by 100 for the conversion of cents to real.

$resultado_total = mysqli_query($con, "SELECT sum(valor) FROM contas WHERE mes ='JANEIRO' ");
$linhas = mysqli_num_rows($resultado_total);

$total_dividido = $linhas / 100;

$html .= '<td class = "total">TOTAL GASTO EM JANEIRO: '.number_format($total_dividido, 2, ',', '.')."</td>";
  • Hello, you are calculating the total spent in January with the total number of rows, as you are using sum, the query always returns a row. 1 / 100 = 0.01. You have to take the return of select to calculate the value you need. Please have a look at this example from w3schools : https://tryphp.w3schools.com/showphpfile.php?filename=demo_db_select_oo

1 answer

0


It’s not working because the mysqli_num_rows returns only the total number of rows in your query. In your case, it is returning 1 divided by 100 = 0,01.

You need to return the searched record, which in your case is a sum, and store the product of the sum in the variable to then divide it.

<?php
    //prepara query - usei um alias para facilitar o retorno (as total)
    $resultado_total = mysqli_query($con, "SELECT sum(valor) as total FROM contas WHERE mes ='JANEIRO' ");
    //transforma em objeto
    $resultado = mysqli_fetch_object($resultado_total);
    //valor
    $valor = $resultado->total;
    $html .= '<td class = "total">TOTAL GASTO EM JANEIRO: '.number_format($valor , 2, ',', '.')."</td>";

?>

Browser other questions tagged

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