Bring column values and sum total with php + mysql

-1

I have the following script that brings the values I need, how do I also bring the total sum of $ row ['value']?

$results = $mysqli->query("SELECT * FROM cv_contratos_dependentes WHERE idcontrato = $idcontrato");
//get all records from add_delete_record table
while($row = $results->fetch_assoc())
{

  echo '<tr id="item_'.$row["id"].'">';
  echo '<td>'.$row["id"].'</td>';
  echo '<td>'.$row["nome"].'</td>';
  echo '<td>'.$row["nascimento"].'</td>';
  echo '<td>'.$row["relacao"].'</td>';
  if($row["valor"]<1){
    echo '<td>SEM CUSTO</td>';
  }else{
    echo '<td>R$ '.$row["valor"].',00</td>';
  };
  echo '</tr>';
}

//close db connection
$mysqli->close();
    
asked by anonymous 11.12.2017 / 17:03

1 answer

2

You can do an SQL query using SUM:

SELECT SUM(valor) as total FROM cv_contratos_dependentes WHERE idcontrato = $idcontrato

Or add the values with a variable in the print loop:

$results = $mysqli->query("SELECT * FROM cv_contratos_dependentes WHERE idcontrato = $idcontrato");
$total = 0;
//get all records from add_delete_record table
while($row = $results->fetch_assoc())
{
  echo '<tr id="item_'.$row["id"].'">';
  echo '<td>'.$row["id"].'</td>';
  echo '<td>'.$row["nome"].'</td>';
  echo '<td>'.$row["nascimento"].'</td>';
  echo '<td>'.$row["relacao"].'</td>';
  if($row["valor"]<1){
    echo '<td>SEM CUSTO</td>';
  }else{
    echo '<td>R$ '.$row["valor"].',00</td>';
  };
  echo '</tr>';
  $total += $row["valor"];
}
echo "Total: ".$total;
//close db connection
$mysqli->close();
    
11.12.2017 / 17:21