How can PHP be used to group MySQL query results based on a specific column?
To group MySQL query results based on a specific column in PHP, you can use the GROUP BY clause in your SQL query. This clause groups rows that have the same values in the specified column. You can then fetch the grouped results and process them as needed in your PHP code.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// SQL query to group results by a specific column
$sql = "SELECT column_name, COUNT(*) as count FROM table_name GROUP BY column_name";
// Execute the query
$result = $mysqli->query($sql);
// Fetch grouped results
while ($row = $result->fetch_assoc()) {
echo "Column: " . $row['column_name'] . " - Count: " . $row['count'] . "<br>";
}
// Close connection
$mysqli->close();
?>