How can the 'group by' clause be used effectively in PHP to consolidate data based on a common attribute?

When using the 'group by' clause in PHP, you can consolidate data based on a common attribute by using it in conjunction with an SQL query. This allows you to group rows that have the same value in a particular column, making it easier to analyze and summarize the data.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->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 = $conn->query($sql);

// Output the 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
$conn->close();