Mac Taylor
Mac Taylor

Reputation: 5168

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 usernames can't be saved , this username exists.");
  }

Even with this code Robert can be registered.

Upvotes: 1

Views: 620

Answers (4)

Mr Coder
Mr Coder

Reputation: 8186

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 .

Upvotes: 0

Canuteson
Canuteson

Reputation: 598

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.");
  }

Upvotes: 0

TJHeuvel
TJHeuvel

Reputation: 12608

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

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

Upvotes: 2

Ignacio
Ignacio

Reputation: 8035

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

Upvotes: 3

Related Questions