Why is it important to specify the columns to be grouped in a MySQL query when using aggregate functions like SUM() in PHP?

When using aggregate functions like SUM() in MySQL queries in PHP, it is important to specify the columns to be grouped because without proper grouping, the query may return incorrect results or throw errors. Grouping ensures that the aggregate function is applied to the correct set of data, grouping together rows based on the specified columns.

$query = "SELECT column1, SUM(column2) FROM table_name GROUP BY column1";
$result = mysqli_query($connection, $query);

if($result){
    while($row = mysqli_fetch_assoc($result)){
        echo $row['column1'] . ": " . $row['SUM(column2)'] . "<br>";
    }
} else {
    echo "Error: " . mysqli_error($connection);
}