What are some best practices for preventing duplicate entries in a database when using PHP and MySQL?

To prevent duplicate entries in a database when using PHP and MySQL, one best practice is to check for existing records before inserting a new one. This can be done by querying the database to see if a record with the same key already exists. Another approach is to set unique constraints on the database table to enforce data integrity and prevent duplicate entries.

// Check if the record already exists before inserting
$query = "SELECT COUNT(*) FROM table_name WHERE column_name = :value";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':value', $value);
$stmt->execute();
$count = $stmt->fetchColumn();

if($count == 0) {
    // Insert the new record
    $insertQuery = "INSERT INTO table_name (column_name) VALUES (:value)";
    $insertStmt = $pdo->prepare($insertQuery);
    $insertStmt->bindParam(':value', $value);
    $insertStmt->execute();
} else {
    echo "Record already exists";
}