Si vous utilisez PDO, vous pouvez simplement intercepter l'exception et vérifier le code d'état, par exemple
// make sure you're set to throw exceptions
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->prepare('INSERT INTO `user` (`email`) VALUES (?)');
try {
$stmt->execute([$email]);
} catch (PDOException $e) {
$errorInfo = $stmt->errorInfo(); // apparently PDOException#getCode() is pretty useless
if ($errorInfo[1] == 1586) {
// inform user, throw a different exception, etc
} else {
throw $e; // a different error, let this exception carry on
}
}
Voir http://dev.mysql. com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry_with_key_name
Le processus serait similaire si vous utilisiez MySQLi
$stmt = $mysqli->prepare('INSERT INTO `user` (`email`) VALUES (?)');
$stmt->bind_param('s', $email);
if (!$stmt->execute()) {
if ($stmt->errno == 1586) {
// inform user, throw a different exception, etc
} else {
throw new Exception($stmt->error, $stmt->errno);
}
}