How to sum the column of a table in PHP

1

Good evening guys,  I bring in a table a result of a select of a bank, but in the result:

  

echo "". $ T_TOTAL. "";

I'm bringing in a variable because I had to make a treatment to get my result.

  

Question: How can I add the result of the variable?

<?php
    echo"<table class='datatable table table-hover table-bordered table-responsiv'>";
    echo"<thead>";
    echo"<tr>";
    echo"<th>CELULAR</th>";
    echo"<th>DESCRIÇÃO</th>";
    echo"<th>TEMPO</th>";
    echo"<th>VALOR</th>";
    echo"</tr>";
    echo"</thead>";
    echo"<tbody>";       
    echo"<tr>";
    while ($row = mysql_fetch_array($query_pesquisa)) {
    $TEMPO=$row['VALOR'];
    $T_TOTAL=$TEMPO / 6 * 0.015 ;
    echo"<td>".$row['CELULAR']."</td>";
    echo"<td>".$row['DESCRICAO']."</td>";
    echo"<td>".$row['MINUTOS']."</td>";
    echo"<td>".$T_TOTAL."</td>";
    echo"</tr>";
      } 
   echo" </tbody>";
   echo" </table>";   

?>
    
asked by anonymous 07.01.2016 / 23:14

2 answers

1

Start the variable with a value of zero.

Within the loop of repetition, increase the value of each sum.

Just do not confuse the subtotal (total unit) with the grand total.

Note that you have created more row <tr></tr> after the loop, to display the grand total.

I'm not sure if this is the result you want. I was only guided by the most logical deduction.

$T_TOTAL = 0;
while ($row = mysql_fetch_array($query_pesquisa)) {
;
$subotal =$row['VALOR'] / 0.09; // 6 * 0.015
$T_TOTAL += $subotal;
echo "<td>".$row['CELULAR']."</td>";
echo "<td>".$row['DESCRICAO']."</td>";
echo "<td>".$row['MINUTOS']."</td>";
echo "<td>".$subotal."</td>";
echo "</tr>";
  }
echo "<tr><td colspan="3" style="text-align:right;">total: </td><td>".$T_TOTAL."</td></tr>";

In the subtotal calculation part, I modified expression 6 * 0.015 by 0.09 because if the expression will always be the same, it is redundant to make PHP always calculate the same value. It is more performatic (performs faster) if you put the value already calculated.

    
08.01.2016 / 12:25
1

Introduction to operators in PHP

An operator is used to perform operations between one or more values (or expressions in programming jargon) and return only one final value. Let's go to the operators.

Arithmetic operators in PHP

<?php
// Declarando os valores das variáveis
$a = 4;
$b = 2;

?>
<h2>Adição</h2>
<p>
<?php

echo $a + $b;

?>
</p>
<h2>Subtração</h2>
<p>
<?php

echo $a - $b;

?>
</p>
<h2>Multiplicação</h2>
<p>
<?php

echo $a * $b;

?>
</p>
<h2>Divisão</h2>
<p>
<?php

echo $a / $b;

?>
</p>
<h2>Módulo(resto da divisão)</h2>
<p>
<?php

echo $a % $b;

?>
</p>
    
07.01.2016 / 23:19