As a rule of thumb, if you cannot manage to write two equal sets of named placeholders, better go for positional ones - there is simply less space for the error:
Integrity constraint violation: 1062 Duplicate entry âhashâ for key âusernameâ in âŚ
I am working on the registration form, the hash is the username if I try to again signup with the same username it shows me the error written above in bold.
I have set the username column to UNIQUE in db, I had also tried to make it INDEX but this doesnât work.
try{
$sqlInsert = "INSERT INTO users(username, email, password, join_date) ";
$sqlInsert.= "VALUES(:username, :email, :password, now())";
// santizing the data
$statement = $db->prepare($sqlInsert);
// add the data into database
$statement->execute(array(':username' => $username,
':email' => $email,
':password' => $hashed_password
));
// check if one new row was created
if ($statement->rowCount() == 1){
$result = "<p style='padding:20px; color: green;'>Registration Successful</p>";
}
} catch(PDOExeception $e){
$result = "<p style='padding:20px; color: red;'>An error occured: " . $e->getMessage()."</p>";
}
} else {
// if the number of errors equal to 1
//if(!empty($form_errors)){
if(count($form_errors) == 1){
$result = "<p style='color:red;'>There was 1 error in the form<br>";
} else {
$result = "<p style='color:red;'>There were " . count($form_errors). " errors in the form <br>";
}
try {
$pdo->prepare("INSERT INTO users VALUES (NULL,?,?,?,?)")->execute($data);
} catch (PDOException $e) {
if ($e->getCode() == 1062) {
// Take some action if there is a key constraint violation, i.e. duplicate name
} else {
throw $e;
}
}
However, I suppose you may want to go a simpler road, by simply adding a select query during user input validation.