How can PHP be utilized to group and display data from a MySQL table based on a specific category efficiently?
To group and display data from a MySQL table based on a specific category efficiently, you can use the GROUP BY clause in your MySQL query to group the data by the desired category column. Then, you can fetch the grouped data using PHP and display it accordingly. This approach allows you to efficiently organize and present data based on specific categories.
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if ($connection === false) {
die("Error: Could not connect. " . mysqli_connect_error());
}
// Query to group data by category
$query = "SELECT category, COUNT(*) as total FROM table_name GROUP BY category";
// Execute query
$result = mysqli_query($connection, $query);
// Display grouped data
while ($row = mysqli_fetch_assoc($result)) {
echo "Category: " . $row['category'] . " - Total: " . $row['total'] . "<br>";
}
// Close connection
mysqli_close($connection);
?>
Related questions
-
PHP user roles permissions
-
PDO placeholders question marks
-
PHP array_unique array_merge