PHP真实的动态计算mysql结果的总和

zbdgwd5y  于 2023-02-21  发布在  PHP
关注(0)|答案(3)|浏览(140)

如何使用html或php或javascript或css将表TD计算为总数?
示例

  1. <table>
  2. <tr><td> 1000 </td></tr>
  3. <tr><td> 2000 </td></tr>
  4. <tr><td> 3000 </td></tr>
  5. <tr><td> TOTAL 6000 </td></tr>
  6. </table>
6ovsh4lw

6ovsh4lw1#

所以先把表存入内存,然后输出总数。

  1. while(... fetch from db ... ) {
  2. $html = '... table row ..';
  3. $total += $row['cost'];
  4. }
  5. echo 'Total: ' . $total;
  6. echo $html; // output table contents
wgeznvg7

wgeznvg72#

只是为了好玩:您 * 可以 * 保持输出原样(至少是顺序,即首先输出项,然后输出总计/总和),然后通过将box-ordinal-group设置为相反顺序来更改元素在浏览器呈现中的位置/顺序。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>...</title>
  5. <style>
  6. #container {
  7. display: -webkit-box;
  8. display: -moz-box;
  9. display: box;
  10. -webkit-box-orient: vertical;
  11. -moz-box-orient: vertical;
  12. box-orient: vertical;
  13. }
  14. #total {
  15. -webkit-box-ordinal-group: 1;
  16. -moz-box-ordinal-group: 1;
  17. box-ordinal-group: 1;
  18. }
  19. #items {
  20. -webkit-box-ordinal-group: 2;
  21. -moz-box-ordinal-group: 2;
  22. box-ordinal-group: 2;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <div id="container">
  28. <div id="items"><!-- though it's before #total in the document -->
  29. <ul><li>a</li><li>b</li><li>c</li><li>d</li><li>e</li></ul>
  30. </div>
  31. <div id="total"><!-- #total will be rendered above #items ...if flexible boxing is supported -->
  32. 1234
  33. </div>
  34. </div>
  35. </body>
  36. </html>
展开查看全部
gxwragnw

gxwragnw3#

我认为@Marc B的答案是你问题标题的更好答案。
如果您希望MySQL数据库的更新实时推送到您的Web页面,则是另一个问题-请查看Rachet Web Sockets for PHP
如果你想要一个javascript的解决方案,只是计算你的总数...
HTML:将相同的类名添加到每个非总计表单元格中。

  1. <tr><td class="amt"> 3000 </td></tr>

在"total"单元格中添加一个带有id的范围。

  1. <tr><td>TOTAL <span id="total">...</span></td></tr>

此时将显示Javascript:
获取所有"amt"细胞的HTMLCollection

  1. const amounts = document.querySelectorAll('.amt');

获取对"total"单元格的引用

  1. const total_cell = document.querySelector('#total');

声明一个变量来保存计算。

  1. Let total = 0;

循环遍历金额,获取每个单元格的内容作为Number,并将该数字添加到"total"的值中。

  1. for (const amt of amounts) {
  2. const number = Number(amt.innerText);
  3. total += number;
  4. }

然后更新"总计"单元格

  1. total_cell.innerText = total;

整个事情...

  1. const amounts = document.querySelectorAll('.amt');
  2. const total_cell = document.querySelector('#total');
  3. let total = 0;
  4. for (const amt of amounts) {
  5. const number = Number(amt.innerText);
  6. total += number;
  7. }
  8. total_cell.innerText = total;
  1. <table>
  2. <tr><td class="amt"> 1000 </td></tr>
  3. <tr><td class="amt"> 2000 </td></tr>
  4. <tr><td class="amt"> 3000 </td></tr>
  5. <tr><td>TOTAL <span id="total">...</span></td></tr>
  6. </table>
展开查看全部

相关问题