dpj0015 2018-05-28 18:58
浏览 53
已采纳

如何计算列中相同结果的数量?

I've developed a database, where i have three sets of columns: - Username - Feeling - Remark

The entry's for feelings are all the same, because they're being selected from a dropdown menu. I'm looking for a way to count the amount of same results and then echo it on a site with PHP, but I can't get any further than this:

<?php
$con=mysqli_connect("localhost","username","password", "database");
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$query = "SELECT COUNT(*) FROM thefeels WHERE feeling = 'Happy'";
$result = mysqli_query($con, $query);

var_dump($result)
?>

In this code I want to count the amount of times happy occurs in a column, but even that is not working. How can I count the amount of times the same results is in a column? So if Happy is there four times and Sad two times it should display:

Happy: 4
Sad: 2
  • 写回答

2条回答 默认 最新

  • dongyilai4214 2018-05-28 20:11
    关注

    This is a basic Counting Rows task. You will find some examples in the official documentation.

    In your case it would be:

    $query = "SELECT feeling, COUNT(*) as count FROM thefeels GROUP BY feeling";
    $result = mysqli_query($con, $query);
    

    Now you can use the "old school" way (which you will find in many totorials):

    while ($row = mysqli_fetch_assoc($result)) {
        echo "{$row['feeling']}: {$row['count']}<br>";
    }
    

    or move forward and separate data fetching from data processing and data output with:

    $feelingCounts = $con->fetch_all(MYSQLI_ASSOC);
    

    And do what ever you need with the fetched data. For example:

    var_dump($feelingCounts);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应