วันเสาร์ที่ 13 สิงหาคม พ.ศ. 2554

การหาผลรวมของตารางข้อมูลหลังจากดึงจาก db แล้วแสดงผลใน php

    data1 | data2
       2    |   1
       3    |   4
       5    |   3
รวม  11  |   8   <-- ใช้ php code หาผลรวมให้อัตโนมัติไม่ต้องคำนวณจาก mysql มา

Code ตัวอย่าง ใช้ Dream ดึงข้อมูลมาแสดงแล้วแก้ไขเพิ่มเติมดังนี้

      <?php do { ?> <tr>
        <td width="30" nowrap="nowrap"><div align="center">
<?php echo $row_rstu03w['dates']; ?>/<?php echo $row_rstu03w['times']; ?></div></td>
        <td width="50" nowrap="nowrap"><div align="right"><?php echo mnum($row_rstu03w['water01']); ?></div></td>
        <td width="50" nowrap="nowrap"><div align="right"><?php echo mnum($row_rstu03w['volumewater']); ?></div></td>
      </tr>          
 <?php   //เริ่มคำนวนหาผลรวมจาก mysql
$aas[] = $row_rstu03w['water01']; //field 1 กำหนดเป็น Array
$aaw[] = $row_rstu03w['volumewater']; //field 2 กำหนดเป็น Array
$sum1=0; //ตั้งค่าเิริ่มต้นให้โปรแกรม
$sum2=0;
for($i=0;$i<$totalRows_rstu03w;$i++){  //นับจำนวน record
$sum1+= $aas[$i];  //เริ่ม loop บวกค่า
$sum2 +=$aaw[$i];
}

 } while ($row_rstu03w = mysql_fetch_assoc($rstu03w)); ?>
    //แสดงผลลัพธ์      
       <tr bgcolor="#FFCC33">
                <td nowrap="nowrap"><div align="center">รวม</div></td>
                <td nowrap="nowrap">
        <?php
 echo mnum($sum1);
?></td>
                <td nowrap="nowrap"><?php
 echo mnum($sum2);
?></td>
              </tr>

ไม่มีความคิดเห็น:

แสดงความคิดเห็น