How can PHP prevent duplicate entries in a database based on a specific field?

To prevent duplicate entries in a database based on a specific field, you can use a combination of PHP and SQL. One common method is to check if the value already exists in the database before inserting a new entry. This can be done by running a SELECT query to search for the value in the specific field. If a matching entry is found, then the new entry should not be inserted.

<?php
// Establish a database connection
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check if the value already exists in the database
$value = "example_value";
$query = "SELECT * FROM table_name WHERE specific_field = '$value'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) == 0) {
    // Insert new entry into the database
    $insert_query = "INSERT INTO table_name (specific_field) VALUES ('$value')";
    mysqli_query($connection, $insert_query);
    echo "New entry inserted successfully.";
} else {
    echo "Value already exists in the database.";
}

// Close the database connection
mysqli_close($connection);
?>