简体   繁体   中英

PHP sum of all variable in while loop while echoing the individual result

Hi i want to display all overall total of $sum2 while displaying the $sum2 this is the example:

<?php $sum2+=$row_acc_rec_pay['counter'] * $row_acc_rec_pay['amount'];
  } while ($row_acc_rec_pay = mysql_fetch_assoc($acc_rec_pay)); ?>

<td>Total:<?php echo $sum2; echo $sum2=0;?></td>

<td> Overall Total=<td>

So the output will be:

test    amount  Sec Course
1   100 3A  BSCS     
3   300 4A  BSCS     
1   100 4B  BSCS     
1   100 3A  BSIS     
3   300 4A  BSIS     
1   100 2A  BSIT     
Total:1000

T-Shirt Fee amount  Sec Course
1   250 3A  BSCS     
3   750 4A  BSCS     
1   250 4B  BSCS     
1   250 3A  BSIS     
3   750 4A  BSIS     
1   250 2A  BSIT     
10  2500    4A  BSIT     
Total:5000


Membership Fee  amount  Sec Course
1   25  3A  BSCS     
3   75  4A  BSCS     
1   25  4B  BSCS     
1   25  3A  BSIS     
10  250 4A  BSIS     
1   25  2A  BSIT     
10  250 4A  BSIT     
Total:675

Overall Total:

i want to add all $sum2 and display it as $overall its really irritating thanks!

You should consider doing some of the math in sql beforehand. I suppose you want something like that:

<?php $sum2=0; $overall=0;?>

<table>
   <thead>
      <tr>
         <th>test</th>
         ...
         <th>Course</th>
      </tr>
   </thead>
   <tbody>
   <?php while($row_acc_rec_pay = mysql_fetch_assoc($acc_rec_pay)): ?>
      <tr>
         <td>...
      </tr>
      <?php $sum2 += $row_acc_rec_pay['counter'] * $row_acc_rec_pay['amount']; ?>
   <?php endwhile; ?>
   </tbody>
</table>
Total: <?= $sum2 ?>;
<?php $overall += $sum2; $sum2 = 0; ?>

[REPEAT FOR THE OTHER TWO TABLES]

Overall Total: <?= $overall; ?>

Just change this line:

<td>Total:<?php echo $sum2; echo $sum2=0;?></td>
//...
<td> Overall Total=<td>

to:

<td>Total:<?php echo $sum2; $totalSum += $sum2; $sum2 = 0;?>
//...
</td> <td> Overall Total=<?= $totalSum ?><td>

And declare $totalSum = 0; before you start your while loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM