【问题标题】:Display MySQL column value count only [duplicate]仅显示 MySQL 列值计数 [重复]
【发布时间】:2021-03-24 06:33:16
【问题描述】:

我如何显示这个查询结果:

从 MySQL 到网页,就像这样:

?

我只想显示计数。我确实通过 PHP 运行了相同的查询,但它返回“2”。 PHP代码如下

 <?php
    //Connection for database                                          
    $conn = mysqli_connect("localhost", "root", "aaaaa", "db");

    $query = "SELECT `gender`,COUNT(`gender`)  FROM `reg` GROUP BY `gender`";

        $result = mysqli_query($conn, $query); 
        
        if ($result) 
        { 
            // it return number of rows in the table. 
            $row = mysqli_num_rows($result); 
            
            if ($row) 
                { 
                    printf("" . $row); 
                } 
            // close the result. 
            mysqli_free_result($result); 
        } 
    
        // Connection close  
        mysqli_close($conn); 
?>

请注意,我已经完成了像 one 这样的其他答案,但我无法真正找到解决方法,我只希望值计数而不是表中所有行的总数,例如算上“男性”。

【问题讨论】:

    标签: php mysql count


    【解决方案1】:

    您正在使用mysqli_num_rows(),它返回结果中的行数,而不是结果中的实际数据。为此,您需要使用mysqli_fetch_assoc()。

    你的可能会变成:

        $query = "SELECT `gender`,
                         COUNT(`gender`) AS `count` 
                  FROM `reg` 
                  GROUP BY `gender`";
    
        $result = mysqli_query($conn, $query); 
        
        if ($result) { 
            while ($row = mysqli_fetch_assoc($result)) {
              $gender = $row['gender'];
              $count  = $row['count'];
              echo "$gender = $count<br>";
            } 
            mysqli_free_result($result); 
        } 
    

    请注意,我稍微更改了您的查询以使计数可访问。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2018-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-29
      相关资源
      最近更新 更多