开发者

prevent duplicated usernames with non-case-sensitive behavior in php/mysql

In my website usernames are saved like this robert and funny thing is that one can registers with the name Robert (Capital R).

How would I prevent these somehow duplicated usernames?

My project is in mysql/php

  if (mysql_num_rows(mysql_query("SELECT username FROM user_table WHERE username='$username'")) > 0){
    die("duplicated username开发者_运维知识库s can't be saved , this username exists.");
  }

Even with this code Robert can be registered.


You should add a UNIQUE index on the username column.

Also, you may find some useful info here: https://stackoverflow.com/search?q=mysql+case+sensitive


Convert them both to the same case and then compare them. As such:

SELECT username FROM table WHERE LOWER(username) = LOWER('$username')


Hopefully you've sanitized the user input for the username to prevent SQL injections, after that, use PHP to LC your usernames before checking for duplicates or inserting the name in the database:

$username = strtolower($username);
if (mysql_num_rows(mysql_query("SELECT username FROM user_table WHERE username='$username'")) > 0){
    die("duplicated usernames can't be saved , this username exists.");
  }


php has very important function but people ignore it in start strtolower , use it at the time of

registering and query hence

  $username = strtolower($username);

you will never face such problem again .

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜