PHPWarningApril 16, 2026
Database Error
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'username' for key 'username'
What This Error Means
This error occurs when you attempt to insert a duplicate value into a column that has a unique constraint, such as a primary key or a unique index.
Why It Happens
This error happens because you're trying to insert a value that already exists in the database column specified as unique. This can occur when you're trying to create a new user with a username that already exists, or when you're trying to insert a duplicate email address into an email column.
How to Fix It
- 1To fix this error, you need to ensure that the value you're inserting does not already exist in the database column specified as unique. You can do this by checking if the value already exists before inserting it, or by modifying your database schema to allow duplicate values.
Example Code Solution
❌ Before (problematic code)
PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (:username, :email)');
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();✅ After (fixed code)
PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $pdo->prepare('INSERT INTO users (username, email) VALUES (:username, :email)
ON DUPLICATE KEY UPDATE email = VALUES(email)');
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();Fix for PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'username' for key 'username'
Browse Related Clusters
Related PHP Errors
Related PHP Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error