How can duplicate data entry be prevented in a MySQL database when using PHP?

Duplicate data entry in a MySQL database can be prevented by setting a unique constraint on the column(s) that should not contain duplicate values. This can be done directly in the database schema. When inserting data using PHP, you can catch any potential duplicate entry errors and handle them accordingly to prevent the duplicate data from being inserted.

<?php
// Establish database connection
$connection = new mysqli('localhost', 'username', 'password', 'database');

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

// Insert data into the database
$query = "INSERT INTO table_name (column1, column2) VALUES ('value1', 'value2')";

if ($connection->query($query) === TRUE) {
    echo "New record created successfully";
} else {
    if ($connection->errno == 1062) {
        echo "Duplicate entry detected, handle accordingly";
    } else {
        echo "Error: " . $query . "<br>" . $connection->error;
    }
}

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