PHP foreach循环只输出mysql表中的最后一个值
问题描述:
我一直在为这个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>";
}
}
?>
答
你的问题是,你的定位可以由数据完全相同的地方进行检索各条:
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;
。
答
试试这个; $ sum_query =“select sum(amount_recieved)from reciepts where category =”。$ cat ['category_id'];
while循环遍历行,foreach遍历列,是你想要发生什么? –
'customer_categories'表中有多少类别? – ajmedway
真的不应该发布此任何更多:http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – CD001