Sum of values of a column in PHP

Asked

Viewed 55 times

-1

I am trying to add the results of an SQL column, but it does not return anything in my function.

Here you have a function that returns all the data in the table registros and the function that should add up the values of the column valor.

<thead>
    <tr>
        <th>ID</th>
        <th>Valor</th>
    </tr>
</thead>
<tbody>
<?php 
    include_once('conexao.php');

    $sql = "SELECT * FROM registros";
    $sql2 = "SELECT SUM(valor) as total FROM registros";

    $resultado = mysqli_query($con, $sql);
    $resultado2 = mysqli_query($con, $sql2);

    while($dados = mysqli_fetch_array($resultado))
        {
    ?>
        <tr>
            <td><?php echo $dados['id']?></td>
            <td><?php echo $dados['valor']?></td>
        </tr>
<?php 
    }
    while($dados2 = mysqli_fetch_array($resultado2))
    {
    ?>
    <div class="col-md-12 float-left mt-3"><?php echo $dados2['total'] ?>   </div>
    <?php 
    }
?>

The first while correctly returns all table rows with id and valor. The second while who calls the $sql2 returns nothing.

I’d like to understand what I’ve done wrong.

  • Where is the closure of tbody and of table? By code, you are placing a div in the middle of the table. Regarding the sum, I tested it here and it worked normally. What is the type of data in the column valor?

1 answer

0

You can also do as follows:

<thead>
    <tr>
        <th>ID</th>
        <th>Valor</th>
    </tr>
</thead>
<tbody>
<?php 
include_once('conexao.php');
$sql = mysqli_query($con, "SELECT * FROM registros");

$total = 0;
while($dados = mysqli_fetch_array($sql)){
    $total += $dados['valor'];
?>
    <tr>
        <td><?php echo $dados['id']?></td>
        <td><?php echo $dados['valor']?></td>
    </tr>
<?php } ?>
<div class="col-md-12 float-left mt-3"><?php echo $total; ?>   </div>

This way we assign $total, for a sum within your loop, with this you will get the result of the total, note that before the loop we set it to zero.

Browser other questions tagged

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