让我们举一个例子,我有一张数据表 Total Points is the sum of two points
现在我已经合并了具有相同名称的行,现在我需要做的是计算两个总点数的总和(总和)并将其显示在下一行中。像这样 Total of 'total points' 这是我的代码
<table>
<tr align="center">
<td>Name</td>
<td>Point1</td>
<td>Point2</td>
<td>Total Points</td>
</tr>
<?php
$select_name = mysql_query("SELECT * FROM test");
while($row = mysql_fetch_array($select_name))
{
?>
<tr align="center">
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['point1']; ?></td>
<td><?php echo $row['point2']; ?></td>
<td><?php echo $row['point1']+$row['point2']; ?></td>
</tr>
<?php } ?>
<tr align="center">
<td>Name</td>
<td>Point1</td>
<td>Point2</td>
<td>Total Points</td>
</tr>
<?php
$select_name = mysql_query("SELECT DISTINCT name FROM test");
while($row = mysql_fetch_array($select_name))
{
$query_table1 = mysql_query("SELECT sum(point1) as sum1,sum(point2) as sum2, sum(point1)+sum(point2) as total FROM test WHERE name='".$row['name']."'");
?>
<tr align="center">
<td><?php echo $row['name']; ?></td>
<td><?php echo mysql_result($query_table1, 0, "sum1"); ?></td>
<td><?php echo mysql_result($query_table1, 0, "sum2"); ?></td>
<td><?php echo mysql_result($query_table1, 0, "total"); ?></td>
</tr>
<?php } ?>
<tr align="center">
<td>Total</td>
<td></td>
<td></td>
<td>???</td>
</tr>
答案 0 :(得分:0)
始终将PHP逻辑与HTML分开。它将允许您编写更强大,更灵活且更易于调试的代码。
完全使用PHP进行查询和计算,直到您将行构建为数组。之后,你应该有类似的东西:
$tbl_1 = [
['abc',20,21,41], ['abc',25,14,39],
['def',22,27,49], ['def',23,18,41]
];
您甚至不需要第二个查询,因为您已拥有所有数据。只需在PHP中操作它以获取所需的统计信息并将它们放在第二个数组中:
$tbl_2 = [
['abc',45,35,80], ['def',45,45,90]
];
要查找总计,可以遍历任一数组的第3列。
只有在完成所有逻辑后,才能继续使用HTML并显示结果。