How can you use GROUP BY in SQL to identify and filter out duplicate entries based on specific columns in PHP?

When working with SQL databases in PHP, you can use the GROUP BY clause to identify and filter out duplicate entries based on specific columns. By grouping the results based on the columns you want to filter duplicates on, you can then use aggregate functions like COUNT() to determine how many times each distinct value appears. This can help you identify and remove duplicate entries from your query results.

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

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

// SQL query to select and filter out duplicates based on specific columns
$sql = "SELECT column1, column2, COUNT(*) as count
        FROM table_name
        GROUP BY column1, column2
        HAVING count = 1";

$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Column 1: " . $row["column1"]. " - Column 2: " . $row["column2"]. "<br>";
    }
} else {
    echo "0 results";
}

$conn->close();