Jika Anda menggunakan PDO, Anda dapat menangkap pengecualian dan memeriksa kode status, misalnya
// 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
}
}
Lihat http://dev.mysql. com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry_with_key_name
Prosesnya akan serupa jika menggunakan 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);
}
}