【问题标题】:PHP foreach while loop how to sum outputPHP foreach while循环如何对输出求和
【发布时间】:2015-09-24 00:04:17
【问题描述】:

查询返回按运算符分组的元素总和(由复选框选中)。

如何总结所有这些值?我尝试使用 array_sum() 但没有奏效,或者我没有正确使用这个函数。 谢谢

<?php

if(isset($_POST['delete']))
{
$ziua=$_POST["date"];
}
else 
{
    $ziua=date('Y-m-d');
}
if(isset($_POST['delete']))
{//check to see if the delete button has been pressed
    if(isset($_POST['box']))
    { //check to see if any boxes have been checked 
        $num = 0;//used to count the number of rows that were deleted
        $box = $_POST['box'];
        foreach ($box as $key =>$val) 
        { //loop through all the checkboxes
                  $num++;

              $sqldel=" SELECT U.username , SUM(L.geometrie1) A from list L,users U where L.user_id='$val' 
              and L.date_posted like '%$ziua%' AND L.user_id=U.id group by U.username  ";//delete any that match id
              $resdel=mysql_query($sqldel);//send the query to mysql

            while($row = mysql_fetch_array($resdel))
            {
            Print "<tr>";
            Print '<td align="center">'. $row['0']. "</td>";
            Print '<td align="center">'. $row['1']. "</td>";
            Print "</tr>";
            }
         }
    }
}
?>
<!-- end snippet -->

【问题讨论】:

  • 结果类似于:admin -> 5, user 8 我想成为 admin -> 5, user 8, total-> 13
  • 一如既往:停止使用已弃用 mysql 扩展。 read the red warning box: 扩展不再维护,以后会被移除。学习使用PDOmysqlii 用于改进)。还要了解准备好的陈述,当你在做的时候。 PDO 更常用(因为它的 API 更好)。 mysqli 提供了一个过程 API 一个面向对象的 API,但是更加混乱。他们都有自己的强项和弱点,所以两个都玩,看你更喜欢哪一个
  • 你很容易受到sql injection attacks
  • 请发布完整代码。我没有看到你要添加的任何地方
  • @NanaPartykar:这就是他首先发布问题的原因:OP 没有在循环中添加任何内容,这就是问题所在:P

标签: php checkbox foreach while-loop sum


【解决方案1】:

在循环之前添加

 $total=0;

在你的循环中添加

  $total += $row[1];

然后在循环后回显

【讨论】:

  • 我的结果是:58,这是我过去 4 天的问题。它以数组的形式返回结果。
  • $total=0; while($row = mysql_fetch_array($resdel)) { 打印 "";打印''。 $行['0']。 "";打印''。 $行['1']。 ""; $total += $row[1];打印“”;回声$总计; }
  • 不,这不是我说的。回显你的总你的循环之后,而不是在它里面。
  • foreach ($box as $key =>$val) { $num++; $sqldel=" SELECT U.username , SUM(L.geometrie1) A from list L,users U where L.user_id='$val' and L.date_posted like '%$ziua%' AND L.user_id=U.id按 U.username 分组"; $resdel=mysql_query($sqldel); $总计=0; while($row = mysql_fetch_array($resdel)) { 打印 "";打印''。 $行['0']。 "";打印''。 $行['1']。 ""; $total += $row[1];打印“”; } } 回声 $total; } }
  • 是我尝试编写的第一个脚本。第一次在这个网站上:)
猜你喜欢
  • 1970-01-01
  • 2015-07-03
  • 2018-05-20
  • 2016-03-20
  • 2012-01-02
  • 2014-10-19
  • 2014-04-15
  • 2018-02-09
  • 2017-05-28
相关资源
最近更新 更多