What are some common mistakes or errors to avoid when using PHP to interact with a database and prevent duplicate entries?

One common mistake when interacting with a database in PHP is not checking for duplicate entries before inserting data, which can lead to duplicate records being added. To prevent this, you can use a SELECT query to check if the data already exists in the database before inserting it.

// Check if the data already exists in the database
$query = "SELECT * FROM table_name WHERE column_name = :value";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':value', $value);
$stmt->execute();

if($stmt->rowCount() == 0) {
    // Data does not exist, insert it into the database
    $insertQuery = "INSERT INTO table_name (column_name) VALUES (:value)";
    $insertStmt = $pdo->prepare($insertQuery);
    $insertStmt->bindParam(':value', $value);
    $insertStmt->execute();
} else {
    // Data already exists, handle the error or display a message
    echo "Duplicate entry found.";
}