人们注册时如何防止重复用户名?PHP/MySQL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17736421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent duplicate usernames when people register? PHP/MySQL
提问by Zippylicious
I have been making a login/register system and I am drawing close to finishing my register portion of code. The only problem I am running into is how to make it so that users cannot register with duplicated usernames. I want it to work so that my database wont accept the information, and it will tell the user about the error. Any help is appreciated.
我一直在制作登录/注册系统,并且即将完成代码的注册部分。我遇到的唯一问题是如何使用户无法使用重复的用户名进行注册。我希望它能够工作,这样我的数据库就不会接受信息,它会告诉用户错误。任何帮助表示赞赏。
My PHP
我的 PHP
<?php
include ('database_connection.php');
if (isset($_POST['formsubmitted'])) {
$error = array();//Declare An Array to store any error message
if (empty($_POST['name'])) {//if no name has been supplied
$error[] = 'Please Enter a name ';//add to array "error"
} else {
$name = $_POST['name'];//else assign it a variable
}
if (empty($_POST['e-mail'])) {
$error[] = 'Please Enter your Email ';
} else {
if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", $_POST['e-mail'])) {
//regular expression for email validation
$Email = $_POST['e-mail'];
} else {
$error[] = 'Your EMail Address is invalid ';
}
}
if (empty($_POST['Password'])) {
$error[] = 'Please Enter Your Password ';
} else {
$Password = $_POST['Password'];
}
if (empty($error)) //send to Database if there's no error '
回答by Walid Naceri
You can do it like this when the user post the username for example and click submit you can write this code or add it to your code with your modification :
例如,当用户发布用户名并单击提交时,您可以这样做,您可以编写此代码或通过修改将其添加到您的代码中:
<?php
$connect = mysql_connect('whatever','whatever','whatever');
$database = mysql_select_db('your dbname');
$username = $_POST['username'];
if(isset($username)){
$mysql_get_users = mysql_query("SELECT * FROM table_name where username='$username'");
$get_rows = mysql_affected_rows($connect);
if($get_rows >=1){
echo "user exists";
die();
}
else{
echo "user do not exists";
}
}
?>
回答by Wasabi
I think something like this is what you're looking for:
我认为这样的事情就是你要找的:
if (isset($_POST['user']))
{
$user = $_POST['user'];
if (mysql_num_rows(yourFunctionForQueryingMySQL("SELECT * FROM tablename WHERE user='$user'")))
echo "Name is taken";
else echo "Name available";
}
回答by itsols
There are two things you should do.
你应该做两件事。
Make the user name a primary key in the database table. This is easily done using phpmyadmin.
Validate prior to insert.
使用户名成为数据库表中的主键。这可以使用 phpmyadmin 轻松完成。
插入前验证。
For the second step, here's an algorithm. You may implement it in your own way using pdo, mysqli or even mysql (although it's not recommended now).
对于第二步,这是一个算法。您可以使用 pdo、mysqli 甚至 mysql 以自己的方式实现它(尽管现在不推荐这样做)。
Algorithm at the end of your code (i.e., if there aren't errors)...
代码末尾的算法(即,如果没有错误)...
Select records that match the USERNAME supplied in the post.
If it exists, give out an error.
If it doesn't exist, insert it.
选择与帖子中提供的 USERNAME 匹配的记录。
如果存在,给出一个错误。
如果它不存在,请插入它。
Hope that helps.
希望有帮助。
回答by natttan
You have to (can) make condition that forbids registration if username already exists.
如果用户名已经存在,您必须(可以)设置禁止注册的条件。
$sql="SELECT username FROM tablename WHERE username='".$username."'";//looking through existing usernames
$resul=mysql_query($sql);
$num = mysql_num_rows($resul);
if ($num !=0){ //If there is already such username...
die("There is user with that username."); // ...kill the script!
} else //continue with the script
回答by null
I used a PDO and class method, may be of some use.
我使用了 PDO 和类方法,可能会有一些用处。
//function for checking if the user already exists in the database
public function userExists($username){
//prepared statements for added security
$query = $this->db->prepare("SELECT COUNT(`id`) FROM `users` WHERE `username`= ?");
$query->bindValue(1, $username);
try{
//execute the query
$query->execute();
$rows = $query->fetchColumn();
//if a row is returned...user already exists
if($rows == 1){
return true;
}else{
return false;
}
//catch the exception
}catch (PDOException $e){
die($e->getMessage());
}
}//end function userExists
note the prepared statements too - definitely the way forward
也请注意准备好的声明 - 绝对是前进的方向
回答by jey batosay
you can do like this :
你可以这样做:
<?php
//---put this code before "if (empty($error))"------
$username = $_POST['username'];
//---if your table user is "table_user" and fieldname username is "username"
$query = 'SELECT username FROM table_user WHERE username = "' . $username . '" LIMIT 1';
$result = mysql_query($query)
$totalNumRowResult = mysql_num_rows($result);
if($totalNumRowResult > 0) {
$error[] = 'User exist';
}
?>
Hope that helps.
希望有帮助。