我一直在爲這個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>";
}
}
?>
while循環遍歷行,foreach遍歷列,是你想要發生什麼? –
'customer_categories'表中有多少類別? – ajmedway
真的不應該發佈此任何更多:http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – CD001