如果你使用的PDO,你可以捕获该异常,并检查状态代码,例如
// 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
}
}
见http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html#error_er_dup_entry_with_key_name
如果使用的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);
}
}
的过程会是类似
您可以尝试插入并捕获'PDOException' /检查相应代码的MySQLi错误。 – Phil
@Phil如何确保查询因为重复的电子邮件而失败? – Razick
1)运行查询以查看是否存在$ email 2)如果您获取行,$ email存在,并且您输出拒绝内容。如果你没有返回行,它不存在,你做任何应该发生的事情。 –