How can PHP be used to display grouped data from a single table effectively?
When displaying grouped data from a single table effectively in PHP, you can use the GROUP BY clause in your SQL query to group the data based on a specific column. You can then fetch the grouped data and display it using PHP to present the information in a structured and organized manner to the user.
// 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 to group data by a specific column
$sql = "SELECT column_name, COUNT(*) as count FROM table_name GROUP BY column_name";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data of each row
while($row = $result->fetch_assoc()) {
echo "Column Name: " . $row["column_name"]. " - Count: " . $row["count"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();