1

Ive been struggling with this foreach loopp for a while now. what i need to do is get sum values from my database table, make some calculations, and then show them as a bar chart using css. but my foreach loop only gives me the last value in the table. Any help will be much appreciated, here is a sample of my code:

<?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>";

            }
    }

?>
Alive to die - Anant
  • 70,531
  • 10
  • 51
  • 98
Immanuel
  • 63
  • 1
  • 5
  • 2
    The while loop loops through the rows, the foreach is cycling through the columns, is that what you want to happen? – Jamie Bicknell Jul 05 '16 at 09:25
  • 1
    How many categories are there in `customer_categories` table? – ajmedway Jul 05 '16 at 09:28
  • 1
    Really should not have to be posting this any more : http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – CD001 Jul 05 '16 at 09:36

2 Answers2

0

Your problem is that you are positioning each bar that may be retrieved by the data in exactly the same place:

        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>";

Floated to the left and absolutely positioned to they will all be overlayed. No need for absolute positioning on these li elements, try removing position:absolute;.

ajmedway
  • 1,492
  • 14
  • 28
0

try this; $sum_query = "select sum(amount_recieved) from reciepts where category =".$cat['category_id'];

bocha lee
  • 1
  • 3