What is the significance of setting a field as UNIQUE in a MySQL database when handling duplicate entries in PHP?

Setting a field as UNIQUE in a MySQL database ensures that duplicate entries are not allowed for that particular field. This helps maintain data integrity and prevents the database from storing redundant information. When handling duplicate entries in PHP, you can catch any errors thrown by MySQL when trying to insert a duplicate entry and handle them accordingly.

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

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

// Insert data into database
$sql = "INSERT INTO table_name (unique_field, other_field) VALUES ('value1', 'value2')";

if ($mysqli->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    if ($mysqli->errno == 1062) {
        echo "Duplicate entry found";
    } else {
        echo "Error: " . $sql . "<br>" . $mysqli->error;
    }
}

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