What is the correct syntax for a SELECT query with GROUP BY in PHP?

When using a SELECT query with GROUP BY in PHP, you need to ensure that the syntax is correct to avoid any errors. The correct syntax for a SELECT query with GROUP BY in PHP includes specifying the columns to select, the table to select from, any conditions to filter the data, and the GROUP BY clause to group the results based on a specific column. Make sure to also handle any potential errors that may arise during the query execution.

<?php

// Establish a connection to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Check for connection errors
if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Define the SELECT query with GROUP BY
$query = "SELECT column1, column2, COUNT(*) as count FROM table_name GROUP BY column1";

// Execute the query
$result = $connection->query($query);

// Handle the results
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "Column1: " . $row["column1"]. " - Column2: " . $row["column2"]. " - Count: " . $row["count"]. "<br>";
    }
} else {
    echo "0 results";
}

// Close the connection
$connection->close();

?>