计数和输出特定词在数据库行中

时间:2018-09-17 19:37:37

标签: php mysql

 id | username | pass | reply         | date    |
 0  | user1    | MD5  | Access-Accept | date 1  | 
 1  | user2    | MD5  | Access-Reject | date 2  |
 2  | user3    | MD5  | Access-Reject | date 3  | 
 3  | user4    | MD5  | Access-Accept | date 4  |  

试图弄清楚如何计算和显示/输出所有      表格中的“ Access-Accept”和“ Access-Reject”。

这是我遇到的问题,当前脚本正在计算所有行,

 <?php
 // start connection 
 $conn = new mysqli($servername, $username, $password, $dbname);
 $sql = 'SELECT * FROM table_1';
 if (mysqli_query($conn, $sql)) {
 echo "";
 } else {
 echo "Error: " . $sql . "<br>" . mysqli_error($conn);
 }
 $result = mysqli_query($conn,$sql);
 $totalsum = mysqli_num_rows($result);
 mysqli_close($con);
 ?>

和html

<?php include 'count-words.php';?>
 <p>Total access: <?=$totalsum?> Total Sessions!</div></p>

在社区帮助下前进,请注意该脚本确实输出了我想要实现的目标。

 mysql> SELECT reply, COUNT(reply) FROM radpostauth GROUP BY reply;
 +---------------+--------------+
 | reply         | COUNT(reply) |
 +---------------+--------------+
 | Access-Accept |          573 |
 | Access-Reject |          233 |
 +---------------+--------------+
 2 rows in set (0.00 sec)

由于php和sql不是我的强属性,因此在输出两行结果时都需要一些帮助,例如:

 <?=$accept?>  
 <?=$reject?>

1 个答案:

答案 0 :(得分:3)

SELECT reply,COUNT(reply) FROM table GROUP by reply

只解释一下:

count(reply)group by为您提供列答复中每个单独值的计数。因此,根据您的示例,您将收到Access-Accept和Access-Reject:

   Reply         Count(Reply)
Access-Accept       2
Access-Reject       2

您似乎正在寻找的东西。

您还可以在AS Reply Count之后加上COUNT(reply),使输出显示Reply Count而不是count(reply)。