2016-07-05 166 views
1

我一直在爲這個foreach循環努力奮鬥了一段時間。我需要做的是從我的數據庫表中獲取總和值,進行一些計算,然後使用css將它們顯示爲條形圖。但我的foreach循環只給了我表中的最後一個值。任何幫助將非常感激,這裏是我的代碼示例:PHP foreach循環只輸出mysql表中的最後一個值

<?php 

    $total_query = "select sum(amount_recieved) from reciepts"; 
    $total_result = safe_query($total_query); 

    $total = mysql_fetch_row($total_result); 

    $query = "select category_id from customer_categories"; 
    $result = safe_query($query); 

    while($cat_id = mysql_fetch_assoc($result)){ 

     foreach ($cat_id as $cat) { 

      $sum_query = "select sum(amount_recieved) from reciepts where category =".$cat.""; 
      $sum_result = safe_query($sum_query); 

      $sum = mysql_fetch_array($sum_result); 

      $percentage = ($sum[0]/$total[0]) * 100; 

      echo " 
       <li title='".$cat.", NGN ".$sum[0].", ".$percentage."%' class='bar' style=' 
        position:absolute; 
        bottom:0; 
        left:1%; 
        float:left; 
        width:7%; 
        height:".$percentage."%; 
        margin-right:1%; 
        margin-left:1%; 
        background:#999;'> 
       </li>"; 

      } 
    } 

?> 
+2

while循環遍歷行,foreach遍歷列,是你想要發生什麼? –

+1

'customer_categories'表中有多少類別? – ajmedway

+1

真的不應該發佈此任何更多:http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – CD001

回答

0

你的問題是,你的定位可以由數據完全相同的地方進行檢索各條:

 echo " 
      <li title='" . $cat . ", NGN " . $sum[0] . ", " . $percentage . "%' class='bar' style=' 
       position:absolute; 
       bottom:0; 
       left:1%; 
       float:left; 
       width:7%; 
       height:" . $percentage . "%; 
       margin-right:1%; 
       margin-left:1%; 
       background:#999;'> 
      </li>"; 

浮動到左邊,絕對定位到他們將被覆蓋。無需對這些li元素進行絕對定位,請嘗試刪除position:absolute;

+1

重要的是你@ajmedway。這解決了我的問題... – Immanuel

+0

@Immanuel我很高興聽到,請你點擊我的答案upvote?謝謝! :) – ajmedway

0

試試這個; $ sum_query =「select sum(amount_recieved)from reciepts where category =」。$ cat ['category_id'];

相關問題