Jeśli używasz PDO, możesz po prostu złapać wyjątek i sprawdzić kod statusu, np.
// 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
}
}
Zobacz http://dev.mysql. com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry_with_key_name
Proces byłby podobny przy użyciu 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);
}
}