Search code examples
phpmysqlincrement

Check if username exists, if so, increment by one


When a username is inserted into my database, such as:

  • John_Smith

I need to check if there is already a John_Smith present. If so, increment it by 1 to become John_Smith_1

So if the following usernames already exist:

  • John_Smith
  • John_Smith_1
  • John_Smith_2
  • John_Smith_3
  • ....up to John_Smith_10

I need the next John_Smith inserted to be incremented to John_Smith_11.

So far, I have searched and come up with this:

  $preferredname= "John_Smith"

        //check for duplicate user names
        $duplicate= check_for_duplicate_username($preferredname);                       

        //if duplicate, increment the preferredname     
        if ($duplicate) 
        {
          $parts = explode("_",$preferredname);

          if (isset($parts[1]))
          $preferredname = $parts[0]."_".$parts[1]."_".($parts[2]+1);

          else $preferredname = $parts[0]."_".$parts[1]."_1";
        }

This, I believe would work for only the first matching usernames. My problem is checking the database for the version of the name with the highest number.. This is my sql:

        function check_for_duplicate_username($name)
{
     // check if username already exists
    $sql = "SELECT * FROM users WHERE user_username=$name";
    //then return duplicates   

Solution

  • While this may not be the best solution in the grand scheme of things, here is an answer that addresses what you were specifically trying to do. The following query returns the number of users with either $name or $name_123 SELECT COUNT(*) FROM users WHERE user_username REGEXP '$name[_0-9]*$'; So if the value is 0 you can simply use $name by itself, otherwise you can use $name."_". + the number returned by the query.

    But as many people have mentioned, prly not the best idea to autoassign usernames (very web 1.0 :P ). I'd recommend email addresses. Another option is to use whatever userid the social app uses along with another field identifying the social app (if you have multiple), and then using an autoincremented id field as the unique primary key..