Search code examples
codeignitercodeigniter-2

multiple column sum in codeigniter table


In my view file i am generating a table as following

<?php
foreach ($accounts as $row) {
  echo '<tr>';
  echo '<td>' . $row['id'] . '</td>';
  echo '<td>' . $row['total_online_sale'] . '</td>';
  echo '<td>' . $row['product_price'] . '</td>';
  echo '<td>' . $row['discount'] . '</td>';
}
?>

I want to generate sum values of those columns in a row surrounded by <tfoot> tag. I don't want to do this operations in model. how should I do it?


Solution

  • You can do so,sum up values in your loop and after loop print these values in <tfoot> tag

    <?php
    $total_online_sale= 0;
    $product_price=0;
    $discount =0;
    foreach ($accounts as $row) {
    $total_online_sale += $row['total_online_sale'];
    $product_price +=$row['product_price'];
    $discount +=$row['discount'];
      echo '<tr>';
      echo '<td>' . $row['id'] . '</td>';
      echo '<td>' . $row['total_online_sale'] . '</td>';
      echo '<td>' . $row['product_price'] . '</td>';
      echo '<td>' . $row['discount'] . '</td>';
      echo '</tr>';
    }
    echo '<tfoot>';
      echo '<tr>';
      echo '<td>&nbsp;</td>';
      echo '<td>' . $total_online_sale . '</td>'; //Grand sum for column total_online_sale 
      echo '<td>' . $product_price . '</td>'; //Grand sum for column product_price 
      echo '<td>' . $discount. '</td>'; //Grand sum for column discount
      echo '</tr>';
    echo '</tfoot>';
    
    ?>