How can the GROUP BY clause in SQL be utilized effectively in PHP to aggregate and display data from a database?
When using the GROUP BY clause in SQL in PHP, you can aggregate and display data from a database by grouping rows that have the same values in specified columns. This can be useful for summarizing data and performing calculations on grouped data. To utilize the GROUP BY clause effectively in PHP, you can execute a SQL query with the GROUP BY clause and then fetch the results to display the aggregated data.
<?php
// 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 column1, SUM(column2) as total FROM table_name GROUP BY column1";
$result = $conn->query($sql);
// Display the aggregated data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Column 1: " . $row["column1"]. " - Total: " . $row["total"]. "<br>";
}
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>