Bring up column values and add up the total with php + mysql

Asked

Viewed 1,542 times

0

I have the following script that brings the values I need, as I do for it 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();

1 answer

2


You can make an SQL query using SUM:

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

Or sum 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();

Browser other questions tagged

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