我正在为我的网站制作登录/注册表单。当我使用新用户名注册为新用户时,尽管数据库为空,但它读起来好像该用户名已经存在。我将尝试引导您完成此代码,但我不确定问题出在哪里。
register.php 我有它,它检查用户输入是否匹配数据库中的任何内容,它将输出正确的错误消息,如果没有匹配,它将转到注册函数将用户注册到数据库中。谢谢 :)
if (isset($_POST['submit'])) {
if(empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email']) || empty($_POST['Fname'])){
$errors[] = 'All fields are required.';
}else{
if ($users->user_exists($_POST['username']) === true) {
$errors[] = 'That username already exists';
}
if(!ctype_alnum($_POST['username'])){
$errors[] = 'Please enter a username with only alphabets and numbers';
}
if (strlen($_POST['password']) <6){
$errors[] = 'Your password must be atleast 6 characters';
} else if (strlen($_POST['password']) >18){
$errors[] = 'Your password cannot be more than 18 characters long';
}
if (filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors[] = 'Please enter a valid email address';
}else if ($users->email_exists($_POST['email']) === true) {
$errors[] = 'That email already exists.';
}
}
if(empty($errors) === true){
$username = htmlentities($_POST['username']);
$password = $_POST['password'];
$email = htmlentities($_POST['email']);
$firstName = htmlentities($_POST['Fname']);
$lastName = htmlentities($_POST['Lname']);
$accountType = $_POST['account_type'];
$users->register($username, $password, $email, $firstName, $lastName, $accountType);
header('Location: register.php?success');
exit();
}
}
这是功能检查用户名和电子邮件是否已经存在
public function user_exists($username) {
$query = $this->mysqli->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bind_param('s', $username);
$query->execute();
$rows = $query->fetch();
if($rows == 1){
return true;
}else{
return false;
}
}
public function email_exists($email) {
$query = $this->mysqli->prepare("SELECT COUNT(`id`) FROM `users` WHERE `email`= ?");
$query->bind_param('s', $email);
$query->execute();
$rows = $query->fetch();
if($rows == 1){
return true;
}else{
return false;
}
}
和注册功能
public function register($username, $password, $email, $firstName, $lastName, $accountType){
global $bcrypt; // making the $bcrypt variable global so we can use here
$time = time();
$ip = $_SERVER['REMOTE_ADDR']; // getting the users IP address
$email_code = $email_code = uniqid('code_',true); // Creating a unique string.
$password = $bcrypt->genHash($password);
$query = $this->mysqli->prepare("INSERT INTO `users` (`username`, `password`, `email`, `ip`, `time`, `email_code`, `firstName`, `lastName`, `accountType`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ");
$query->bind_param('ssssissss',$username, $password, $email, $ip, $time, $email_code, $firstName, $lastName, $accountType);
$query->execute();
}