How can the GROUP BY clause be used to group results in PHP?

The GROUP BY clause in SQL is used to group results based on a specific column or expression. In PHP, you can use the GROUP BY clause in conjunction with a SQL query to group results from a database table. This can be useful when you want to aggregate data or perform calculations on grouped data. Example PHP code snippet:

<?php
// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// SQL query with GROUP BY clause
$sql = "SELECT column_name, COUNT(*) as count FROM table_name GROUP BY column_name";

// Execute the query
$result = $connection->query($sql);

// Output the grouped results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Column: " . $row["column_name"]. " - Count: " . $row["count"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$connection->close();
?>