PHP foreach loop only produces the last value of the mysql table

advertisements

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

            }
    }

?>


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