Home > Article > Backend Development > How to use data aggregation functions in PHP
The data aggregation function is a function used to process multiple rows of data in a database table. Using data aggregation functions in PHP allows us to easily perform data analysis and processing, such as sum, average, maximum value, minimum value, etc. Below we will introduce how to use data aggregation functions in PHP.
1. Introducing commonly used data aggregation functions
2. Use data aggregation functions
The following will take a student table as an example to introduce how to use data aggregation functions.
We can use the COUNT() function to calculate the total number of records in the student table.
//连接数据库 $conn = mysqli_connect("localhost", "root", "", "testdb"); //SELECT COUNT(*) AS total FROM students $sql = "SELECT COUNT(*) AS total FROM students"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "学生表中总共有 ".$row['total']." 条记录。"; } }
We can use the SUM() function to count the sum of grades in the student table.
//SELECT SUM(score) AS score_total FROM students $sql = "SELECT SUM(score) AS score_total FROM students"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "学生表中成绩总和为:".$row['score_total']." 分。"; } }
We can use the AVG() function to calculate the average of the grades in the student table.
//SELECT AVG(score) AS score_avg FROM students $sql = "SELECT AVG(score) AS score_avg FROM students"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "学生表中成绩平均分为:".$row['score_avg']." 分。"; } }
We can use the MAX() function to get the highest score in the student table.
//SELECT MAX(score) AS max_score FROM students $sql = "SELECT MAX(score) AS max_score FROM students"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "学生表中成绩最高分为:".$row['max_score']." 分。"; } }
We can use the MIN() function to get the lowest score in the student table.
//SELECT MIN(score) AS min_score FROM students $sql = "SELECT MIN(score) AS min_score FROM students"; $result = mysqli_query($conn, $sql); if(mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_assoc($result)) { echo "学生表中成绩最低分为:".$row['min_score']." 分。"; } }
3. Summary
The data aggregation function is a very practical function. Using the data aggregation function in PHP can easily perform data analysis and processing. This article introduces the use of commonly used data aggregation functions through the above examples. I hope it will be helpful to you.
The above is the detailed content of How to use data aggregation functions in PHP. For more information, please follow other related articles on the PHP Chinese website!