user12236643
user12236643

Reputation:

Total of column in displayed result in PHP

I have a table 'tblexam' which contains State,city,candidate.I want to fetch the data from this table using where clause.I am able to fetch the data but i want to add the sum of Candidate at the last row(As Shown In Picture) how can i do that .

$sql="SELECT * 
      FROM tblexam
      WHERE state='UP'";

$cnt=1;
if($query->rowCount() > 0)
{
    foreach($results as $result) {      
        $cnt=$cnt+1; ?>                                      
        <tr class="odd gradeX">
        <td class="center"><?php echo htmlentities($cnt);?></td>
        <td class="left"align="left"><?php echo htmlentities($result->state);?></td>
        <td class="center" align="left"><?php echo htmlentities($result->city);?></td>
        <td class="center"align="left"><?php echo htmlentities($result->candidate);?></td>
   <?php } ?>                       
        <td class="center"align="left"><?php echo htmlentities($result->Total);?></td>

    </tbody>
 </table>

enter image description here

Upvotes: 0

Views: 111

Answers (2)

Ajith
Ajith

Reputation: 2666

Add total while iterating through rows and display it outside the loop, Sample code is given below

$sql     = "SELECT * FROM tblexam WHERE city='UP'";
$result  = $conn->query($sql);
$numRows = $result->num_rows;
if ($numRows> 0) {
    $total = 0;
    echo '<table border="1" cellpadding="5" cellspacing="0">';
    echo '<tr>';
    echo '<th>state</th>';
    echo '<th>city</th>';
    echo '<th>candidate</th>';
    echo '</tr>';
    while($row = $result->fetch_assoc()) {

            $total+=$row['candidate'];
            echo '<tr>';
            echo '<td>'.$row['city'].'</td>';
            echo '<td>'.$row['state'].'</td>';
            echo '<td>'.$row['candidate'].'</td>';
            echo '</tr>';

    }

    echo '<tr>';
    echo '<td>Total</td>';
    echo '<td>&nbsp;</td>';
    echo '<td>'.$total.'</td>';
    echo '</tr>';

    echo '<table>';
} 

Upvotes: 1

Verro
Verro

Reputation: 46

Before you start looping the data you can create a variable which you set to 0, inside the loop you can add the result's total to this variable, after the loop, the variable will contain the grand total:

$total = 0;
foreach($results as $result) {
    $total += (int)$result->Total;
    ...
}
// $total = 1425

Upvotes: 1

Related Questions