您好我已经创建了一个注册/注册表单,用于注册新用户并将其添加到我的数据库中。 然而,在测试时,我发现有人可以使用已经使用的用户名进行注册。 这是我的代码:
<?php
require('db.php');
// If form submitted, insert values into the database.
if (isset($_REQUEST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, password, email, trn_date)
VALUES ('$username', '".md5($password)."', '$email', '$trn_date')";
$result = mysqli_query($con,$query);
if($result){
echo "<div class='form'>
<h3>You are registered successfully.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}
?>
我尝试更改查询语句以从数据库中选择所有用户名并检查查询结果是否返回相同的用户名输入,如果是,则返回“username taken”,如果不是,则在运行上面显示的instert声明并打印成功注册的消息。
任何帮助?
答案 0 :(得分:1)
好的,这就是你能做的。
首先,为您的用户名栏创建一个唯一索引,如下所示:
CREATE TABLE users (
... create columns...
PRIMARY KEY (user_id),
UNIQUE (username),
INDEX login (username, password)
);
然后在您的PHP脚本中进行注册,检查用户名是否存在:
$q = "SELECT user_id FROM users WHERE username='$filtered_username_variable'";
$r = mysqli_query ($con, $q);
if (mysqli_num_rows($r) == 0) { // No: of rows returned. 0 results, Hence the username is Available.
//code to INSERT into Database
} else { // The username is not available, print error message.
echo 'Uh-oh, This username has already been registered.';
}