Current Location: Home> Latest Articles> PHP PDO Guide: Grouping and Aggregation Queries Explained

PHP PDO Guide: Grouping and Aggregation Queries Explained

M66 2025-09-30

Introduction

In web application development, it's common to need grouping and aggregation operations on database data. Using PHP's PDO (PHP Data Objects) extension simplifies database handling while improving code security and maintainability. This article explains how to perform data grouping and aggregation queries using PDO with practical code examples.

Connecting to a Database with PDO

Before performing grouping and aggregation queries, we need to establish a database connection. The example below demonstrates how to connect to a MySQL database using PDO:

$dsn = 'mysql:host=localhost;dbname=mydatabase;';
$user = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $user, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Successfully connected to the database!";
} catch (PDOException $e) {
    echo "Database connection failed: " . $e->getMessage();
}

This code establishes a PDO connection and sets the error mode to exceptions, allowing clear error reporting if something goes wrong.

Data Grouping Query

Suppose we have a students table containing student names and their class assignments. To count the number of students per class, we can use the following SQL query with PDO:

$sql = "SELECT class, COUNT(*) as student_count FROM students GROUP BY class";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

    foreach ($result as $row) {
        echo "Class: " . $row['class'] . ", Number of Students: " . $row['student_count'] . "<br>";
    }
} catch (PDOException $e) {
    echo "Query failed: " . $e->getMessage();
}

Using the GROUP BY clause, we can efficiently retrieve the student count for each class.

Aggregation Calculations

Beyond grouping, aggregation operations like SUM, AVG, MAX, and MIN are often required. The example below demonstrates how to perform aggregation queries using PDO:

$sql = "SELECT COUNT(*) as student_count, AVG(score) as avg_score, MAX(score) as max_score, MIN(score) as min_score FROM students";

try {
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    echo "Total Students: " . $result['student_count'] . "<br>";
    echo "Average Score: " . $result['avg_score'] . "<br>";
    echo "Highest Score: " . $result['max_score'] . "<br>";
    echo "Lowest Score: " . $result['min_score'] . "<br>";
} catch (PDOException $e) {
    echo "Query failed: " . $e->getMessage();
}

Here, we retrieve multiple statistical results in a single query, including total students, average score, maximum score, and minimum score.

Conclusion

In this article, we demonstrated how to connect to a database using PHP PDO and perform data grouping and aggregation queries. These techniques are essential for handling complex data analysis tasks efficiently, enabling developers to build robust and flexible data processing logic.