<分区>
所以,我有一个注册表单,我希望所有用户名(电子邮件地址)都必须是唯一的,我这样做是为了使数据库条目必须是唯一的,但是用户得到的错误是我的通用错误一个(请参阅 $message),我可以将其更改为另一条消息,但是用户将不知道该帐户是否由于服务器端错误或电子邮件地址重复而未创建。
$message = 'Sorry there must have been an issue creating your account';
我一直在努力获得的是一种自定义错误的方法,当用户名已被使用时,它会显示类似以下内容的内容:“抱歉,此电子邮件已被使用”。
下面是我的注册表格的代码(我没有做这个):
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: restricted.php");
}
require 'database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['firstname']) && !empty($_POST['surname'])):
// Enter the new user in the database
$sql = "INSERT INTO users (email, password, firstname, surname) VALUES (:email, :password, :firstname, :surname)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':firstname', $_POST['firstname']);
$stmt->bindParam(':surname', $_POST['surname']);
if( $stmt->execute() ):
$message = 'Successfully created new user';
else:
$message = 'Sorry there must have been an issue creating your account';
endif;
endif;
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<?php include '../header.php'; ?>
</head>
<body>
<?php if(!empty($message)): ?>
<p><?= $message ?></p>
<?php endif; ?>
<h1>Register</h1>
<span>or <a href="login.php">login here</a></span>
<form action="register.php" method="POST">
<input type="text" placeholder="Enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="text" placeholder="Enter your first name" name="firstname">
<input type="text" placeholder="Enter your surname" name="surname">
<input type="submit">
</form>
</body>
</html>