How can GROUP BY be used to efficiently count the number of posts per category in a PHP forum?

To efficiently count the number of posts per category in a PHP forum, you can use the GROUP BY clause in SQL to group posts by category and then use the COUNT function to get the total number of posts in each category. This allows you to retrieve the data in a structured format without the need for additional processing in PHP.

// Assuming $conn is your database connection

$query = "SELECT category, COUNT(*) as post_count FROM posts GROUP BY category";
$result = mysqli_query($conn, $query);

if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "Category: " . $row['category'] . " - Posts: " . $row['post_count'] . "<br>";
    }
} else {
    echo "No posts found.";
}