How does PDO in PHP simplify the process of grouping query results, and what advantages does it offer in terms of data structure?

PDO in PHP simplifies the process of grouping query results by allowing us to fetch data in a structured way using fetchAll() method. This method returns an array containing all of the remaining rows in the result set, making it easier to group and manipulate the data as needed. This approach offers advantages in terms of data structure by providing a more organized and manageable way to work with query results.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare and execute the query
$stmt = $pdo->prepare("SELECT category, COUNT(*) as total FROM products GROUP BY category");
$stmt->execute();

// Fetch all rows as an associative array
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through the results and display the data
foreach ($results as $row) {
    echo $row['category'] . ': ' . $row['total'] . ' products<br>';
}