What is the significance of using GROUP BY in a MySQL query when counting rows in different categories in PHP?

When counting rows in different categories in PHP using MySQL, it is important to use the GROUP BY clause in the SQL query. This allows you to group the results based on a specific column, such as category, and then use aggregate functions like COUNT() to get the count of rows in each category. Without using GROUP BY, the count would be inaccurate as it would not take into account the different categories.

// Connect to database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Query to count rows in different categories
$query = "SELECT category, COUNT(*) AS count FROM table_name GROUP BY category";

// Execute query
$result = $mysqli->query($query);

// Loop through results
while ($row = $result->fetch_assoc()) {
    echo $row['category'] . ": " . $row['count'] . "<br>";
}

// Close database connection
$mysqli->close();