How can PHP be used to efficiently handle and display data grouped by specific criteria in a web application?
To efficiently handle and display data grouped by specific criteria in a web application using PHP, you can use the `GROUP BY` clause in SQL queries to group data based on a specific column. You can then use PHP to loop through the grouped data and display it in a structured format on the web page.
<?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);
}
// Query to select data grouped by specific criteria
$sql = "SELECT category, COUNT(*) as total FROM products GROUP BY category";
$result = $conn->query($sql);
// Display grouped data
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Category: " . $row["category"]. " - Total: " . $row["total"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What role does the count() function play in determining the display of navigation elements in PHP scripts?
- How can PHP developers ensure that calculation results are displayed in the correct location on the page after processing?
- How can developers ensure the security of session management when using session_id() and SID in PHP?