如何在php中以正确的方式获取count(*)

时间:2019-07-04 04:29:13

标签: php mysql database mysqli

我尝试用php count()从数据库中获取数据,但它没有显示全部数据,但显示了数据。

这就是我的计算方式

$query = "SELECT 
        mitra.*,         
        user.username, 
        user.privilege, 
        user.name 
    FROM 
        mitra
    INNER JOIN 
        user ON mitra.id_user = user.id "

$result = $connection->query($query);

if ($result->num_rows > 0) {
    foreach ($result as $row) :
        $id = "" . $row["id"] . "";
        $total = "" . $row["total_puas"] . "";
        $privilege = "" . $row["privilege"] . "";

        if ($privilege == 2) :
            $calculate = $total / count($id);
            var_dump(count($id));
        endif;
    endforeach;
}

===================
=   id =  total   =
=  1   =   45.84  =
=  2   =   75.45  =
=  3   =   34.54  =
===================

当我使用var_dumb时,它显示int(1)int(1)int(1)而不是int(3)我想要的。

实际上,我想用$calculate中应该有浮点数的数据来计算$total,而我想用$total除以count id中的数据

有什么解决方法可以计算$total中的金额,并可以用count $id来区分,该值应该为3?请帮助

我从该表示例中真正尝试做的事情就像45.84 + 75.45 + 34.54 / 3

3 个答案:

答案 0 :(得分:3)

听起来像您想要查询中带有COUNT()的{​​{1}}。在PHP中执行GROUP BY总是会产生一个,因为它不是值数组。

count($id)

根据您更新的问题,输出将变得更加清晰。根据输出数据和所需的结果,您需要计算所有$query = "SELECT COUNT(id) as cnt, id, total_puas FROM table GROUP BY id"; $result = $connection->query($query); if ($result->num_rows > 0) { while ($row = $result->fetch_assoc()) { $calculate = $row["total_puas"] / $row['cnt']; echo $row['id']." has a count of ".$row['cnt'].", a total of ".$row['total_puas']." and calculated to ".$calculate."<br />\n"; } } 的总和除以行数。您可以直接在一个查询中执行此操作,例如

total_paus

答案 1 :(得分:2)

您可以尝试以下代码:

$scope.staff_update = [
   {
      'id': '1',
      'title': 'Staff 1',
      'status': 'chosen'
   },
   {
      'id': '2',
      'title': 'Staff 2',
      'status': 'chosen'
   },
   {
      'id': '3',
      'title': 'Staff 3',
      'status': 'none'
   },
   {
      'id': '4',
      'title': 'Staff 4',
      'status': 'none'
   }
];

$scope.updateStaff = {staffs_id: ['1','2']};

答案 2 :(得分:0)

您可以尝试以下代码:

$query = "SELECT * FROM table"
$result = $connection->query($query);

if ($result->num_rows > 0) {
    $total = 0.0;
    foreach ($result as $row) :
        $id = "" . $row["id"] . "";
        $total = $total + $row['total'];
    endforeach;
    $calculate = $total / $result->num_rows;
    echo $total.<br>;
    echo $calclulate;
}