我遵循的数据库结构。
id email lat long point balance date
1 33 1.00 2.00 0 empty date
2 34 8.00 3.00 -1 empty date
3 33 7.00 4.00 2 empty date
4 33 6.00 5.00 0 empty date
5 33 6.33 5.43 -1 empty date
所以我想显示所有记录,其中电子邮件ID是33,但是必须在每行中显示余额。
In first row it's balance is 0
second row it's balance is 2
third row it's balance is 2
four row it's balance is 1
所以我的php代码看起来像这样,但无法获得正确的平衡:
echo "<table width='100%' cellpadding='5' cellspacing='0' border='1'>";
echo "<tr>";
echo "<td class='tdhead' valign='top' width='100'><b>Date</b></td>";
echo "<td class='tdhead' valign='top' width='100'><b>Lattitude</b></td>";
echo "<td class='tdhead' valign='top' width='50'><b>Longitude</b>
</td>";
echo "<td class='tdhead' valign='top' width='50'><b>Point</b>
</td>";
echo "<td class='tdhead' valign='top' width='50'><b>Balance</b>
</td>";
echo "</tr>";
while($res = mysql_fetch_array($park_history))
{
$lat = $res['lat'];
$long = $res['long'];
$point = $res['point'];
$date = $res['date'];
$balance = 0;
$sum = mysql_query("SELECT SUM(point) AS points FROM balance WHERE email =
'".$_SESSION['SESS_ID']."'");
$sum_res = mysql_fetch_array($sum);
$sum = $sum_res['points'];
echo "<tr>";
echo "<td class='tdhead2' valign='top'>$date</td>";
echo "<td class='tdhead2' valign='top'>$lat</td>";
echo "<td class='tdhead2' valign='top'>$long</td>";
echo "<td class='tdhead2' valign='top'>$point</td>";
echo "<td class='tdhead2'
valign='top'>$sum</td>";
echo "</tr>";
}
我相信可以使用mysql sum函数来完成。您能给我解决方案或建议吗?谢谢。
最佳答案
MySQL sum
函数不会执行您想要的操作-但不是必须执行的操作-有一种更简单的方法可以使用已经获取的结果来完成任务。
由于您已经在要处理的行上添加了$point
,因此只需将其添加到计数器中并从那里开始。实际上,您正在每行进行一次多余的db调用。
采用:
$sum = 0;
while ( $res = mysql_fetch_array($park_history) ) {
/* yada yada */
$point = $res['point'];
$sum += $point;
echo /* your table here */
}
您可以完全删除以下行:
$sum = mysql_query( ... );
$sum_res = mysql_fetch_array($sum);
$sum = $sum_res['points'];
$total
将按照您的描述保持运行点计数,并且不会在每个循环中查询您的数据库。关于php - mysql sum函数结果显示在每一行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19603077/