0

我正在寻找将总和值放在 HTML 表格上方的简单、最佳实用方法。

通常循环可以在循环完成后生成总和,该总和位于所有结果表的下方。当表格很长并且我们每次都需要向下滚动才能看到销售额的总和时,这可能会非常困难。我需要运行两个循环还是有什么技巧可以做到这一点?任务看起来很简单。在下面的代码中,我将所有订单的数量和总销售额值相加:

$lp=1; $total=0; $total_qt=0;
while ($record = mysql_fetch_array($result)){
$total += $record['Total'];
$total_qt += $record['Qt'];
echo '<tr style="background-color:'. ((next($colour) == true) ? current($colour) :     reset($colour)).'">
<td> ' . $lp++ . '</td>
<td class="bolder"> ' . $record['Name'] . '</td>
<td> ' . $record['Product'] . '</td>';
if ($invoice=="on") echo '<td style="font-size:11px">' . $record['Invoice'] . '</td>';
echo '<td> ' . $record['despatched'] . '</td>
<td> ' . $record['Qt'] . '</td>
<td> ' . $record['Price'] . '</td>
<td class="align_right"> ' . $record['Total'] . '</td>';

echo '</tr>';
}
echo '</table><div class="stat_total">Qt: '.$total_qt.'  Total: &pound;'.$total.'</div>    </div>';
4

2 回答 2

1

通过使用SUM()SQL 函数,您无需运行 PHP 即可访问总和:

SQL

SELECT SUM(Total) FROM Orders

于 2012-09-29T16:21:13.147 回答
1

您可以在循环中使用变量来存储您的输出,而不是使用echo它,当您完成循环时echo,存储的结果包含它们之前和之后的总计。像这样:

$lp=1; $total=0; $total_qt=0;
$output = ''; //here you temporarily save your output
while ($record = mysql_fetch_array($result)){
$total += $record['Total'];
$total_qt += $record['Qt'];
$output .= '<tr style="background-color:'. ((next($colour) == true) ? current($colour) :     reset($colour)).'">
<td> ' . $lp++ . '</td>
<td class="bolder"> ' . $record['Name'] . '</td>
<td> ' . $record['Product'] . '</td>';
if ($invoice=="on") $output .= '<td style="font-size:11px">' . $record['Invoice'] . '</td>';
$output .= '<td> ' . $record['despatched'] . '</td>
<td> ' . $record['Qt'] . '</td>
<td> ' . $record['Price'] . '</td>
<td class="align_right"> ' . $record['Total'] . '</td>';

$output .= '</tr>';
}
//Now you can put a div with the Total both at the start and end of the table 
echo '<div class="stat_total">Qt: '.$total_qt.'  Total: &pound;'.$total.'</div>';
echo $output . '</table>';
echo '<div class="stat_total">Qt: '.$total_qt.'  Total: &pound;'.$total.'</div>    </div>';
于 2012-09-29T16:21:18.117 回答