开发者

How to tell if a username is already taken in a database

How do I tell if a username in a database is already taken with php for a 开发者_开发技巧signup page?


something like:

$sql = 'SELECT * FROM USERS where user_name = "'.$_GET['username'].'"';
$res = mysql_query($sql);
if($res && mysql_num_rows($res)>0){
  echo 'taken';
} else {
  echo 'free';
}


Conceptually, you would probably use GET for the username field to a script that runs a query against the database with a WHERE clause, where username is equal to the GET variable. If it returns a match, the username is taken.

There's a lot of ways to do this, if you had a more specific specification, I could elaborate even more.

We have some very interesting points from the comments; from my experience with UI, I'd definitely do this check "inline", meaning that you could check the status of the username via AJAX to give some feedback instantly as to whether or not the username is taken. In that case, you would most definitely use GET.

If that is not your intent and you are submitting any sensitive information (in this case, probably a password) in your signup form, use POST (see this question: GET versus POST in terms of security?)


I think you're looking for something like this.

$username = $_POST['username'];
$query = sprintf("SELECT * FROM users WHERE user='%s'", mysql_real_escape_string($username));
$result = mysql_query($query);

if(!$result) {
    // Some kind of error occurred with your connection.
} else {
    if(mysql_num_rows($result) > 0) {
        // Throw an error, the username exists
    } else {
        // Good to go...
    }
}


Try this maybe it can help you of course you need to trim the input

//first check if it's not empty input
if (empty($_POST['userName'])) {
        $userNameErr = "User name required";
    } else {
        $userName = $_POST['userName'];
        $getData= $db->prepare("SELECT * FROM tableName WHERE user_name=?");
        $getData->bind_param('s', $userName);
        if($getData->execute()){
            $results = $getData->get_result();
            if($results->num_rows>0){
                $userNameErr = "User name already token";
            }
        }
        //check the input characters
        if (!preg_match("/^[0-9_a-zA-Z]*$/", $userName)) {
            $userNameErr = "Only letters, numbers and '_' allowed";
        }
    }

hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜