PHP 显示 MySQL 查询结果

标签 php mysql

我正在尝试解决这个问题,我已经搜索了谷歌,但我不知道如何去做。

我有一个名为 Affiliates 的表。 在此表中我有 3 个字段

+---------+-----------------+-------+
| user_id | AffID           | total |
+---------+-----------------+-------+
|       1 | Aff1            |     10|
|       2 | Aff1            |     10|
|       3 | Aff2            |     5 |
|       4 | Aff2            |     5 |
+---------+-----------------+-------+

我想回显以下结果:

Aff1 20
Aff2 10

如您所见,它对 AffID 进行了分组并添加了总值(value)。

现在,如果我向 AffID 添加另一个附属机构,例如总共 10 个 AffID3,它必须自动显示它。

Aff1 20
Aff2 10
Aff3 10

我知道我需要使用 groupby 作为 AffID ,并使用 Sum 来计算总数,但是我如何回显结果? (循环?)

最佳答案

尝试这样的事情

    //db connection

     global $conn;

        $servername = "localhost";  //host name

        $username = "username"; //username

        $password = "password"; //password

        $mysql_database = "dbname"; //database name

    //mysqli prepared statement 

        $conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());

        mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");

        $stmt = $conn->prepare("select sum(total) as Total,AffID,user_id  from Affiliates  group by AffID order by user_id ASC");

                    $stmt->execute();
                    $get_result= $stmt->get_result();
                    $row_count= $get_result->num_rows;

                    if($row_count>0)
                    {
                       while($row=$get_result->fetch_assoc())
                       {

                          echo $row['user_id ']."     ".$row['AffID']."   ".$row['Total']."<br/>";


                       }


                    }
                    $stmt->close();
                     $conn->close();

关于PHP 显示 MySQL 查询结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807106/

相关文章:

php - 使用php从mysql数据库中获取Json

php - 是否可以为 mysql 中的表设置到期日期/时间?

mysql - 如何更新此 SQL 查询以提供我想要的结果?

PHP : Preg_match not work when have "/"

php - MySQL PHPExcel 查询执行时间太长

php - 图像未显示在 .blade 文件中

mysql - 如何在 MySQL 中进行递归 SELECT 查询?

mysql - AWS SSH 和 RDS 权限被拒绝 - 公钥

mysql - 如何仅选择 bigint 的日期部分?

mysql - Drupal 在它的数据库中放了什么?