How can PHP be used to prevent duplicate entries in a database when user input is stored?

When storing user input in a database, it's important to prevent duplicate entries to maintain data integrity. One way to achieve this is by checking if the input already exists in the database before inserting it. This can be done by querying the database to see if a record with the same input already exists.

// Check if the user input already exists in the database
$input = $_POST['user_input'];
$query = "SELECT * FROM table_name WHERE column_name = '$input'";
$result = mysqli_query($connection, $query);

if(mysqli_num_rows($result) > 0) {
    echo "Entry already exists in the database";
} else {
    // Insert the user input into the database
    $insert_query = "INSERT INTO table_name (column_name) VALUES ('$input')";
    mysqli_query($connection, $insert_query);
    echo "Entry successfully added to the database";
}