php - How to know which entry is duplicated? (For example username + email)
Get the solution ↓↓↓Solution:
You can check value in db or grab colum name in the error message for your users.
try{
$pdo->query("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','[email protected]')");
} catch (PDOException $e) {
if (preg_match("/Duplicate entry .+ for key '(.+)'/", $e->getMessage(), $matches)) {
throw new CustomException($matches[1]." already exist");
} else {
throw $e;
}
}
also maybe you prefer to use exec command for "non result query string".
$affectedRow = $pdo->exec("INSERT INTO `table`(`username`,`email`) VALUES ('Superman','[email protected]')");
Answer
Solution:
Thanks for the idea. Didnt think that error could give me this info. So it will result as this :
try {
$query = $this->dbh->prepare('INSERT INTO users (username,email) VALUES ("test", "test")');
$result = $query->execute();
} catch (PDOException $e) {
if( $e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062' ){
if( strpos($e->getMessage(), 'username') == true ) $result = 'duplicate_username';
elseif( strpos($e->getMessage(), 'email') == true ) $result = 'duplicate_email';
} else {
throw $e;
$return = false;
}
}
Basically doing the job.
Thanks,
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: failed to create image decoder with message 'unimplemented'
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.