-->

Is mysql auto increment safe to use as userID?

2019-02-12 14:43发布

问题:

I am working on website that allows people to create profiles online. I was wondering if it is the right choice to use MySQL AUTO_INCREMENTed IDs as my user ids. Also bearing in mind that I might have to duplicate the database across multiple servers one day?

e.g. would you use this method for userIds on a website like Twitter or Facebook?


I have tried generating userIds with PHP before. I used something like this:

function generateID() {
      $possible = "1234567890";
      $code = "";
      $characters = mt_rand(7,14);
      $i = 0;
      while ($i < $characters) { 
            $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
            $i++;
      }
      return $code;
}

This gave the type of values I needed, but I always had to check from the DB if that ID does not exist yet.

Isn't there a better approach?

回答1:

Is mysql auto increment safe to use as userID?

If your security system is reliable, basically, yes. But generally, web developers feel uncomfortable exposing IDs that allow guessing other IDs by just incrementing or decrementing a number. Many resort to random, multi-digit IDs instead.

On a more obscure note, numeric IDs may also allow competitors to estimate your growth by keeping track of how the incremental value increases.



回答2:

No, it is not a good idea because auto_increment ids are not easily portable. For your user ids you want ids that can be backed up, restored, moved between database instances, etc. without worrying about collision of ids.

It would be better to generate a unique number or alpha-numeric string using something like UUID.



回答3:

Given you are planning ahead and potentially would be distributing the data across databases, you would be better considering using the UUID() function to get unique identifiers. This makes the merging of data far easier in the future.



回答4:

personally, yes I think so, up until a point. When duplicating a database table with an auto increment field, I think the field retains its max value (depending on how you duplicate it, the scenario I have in mind is mysqldump with data) so when you add a new row, it will be assigned the next ID.

However if you were to have this running on several databases at once, and they weren't replicated, you would need some other way of generating IDs to avoid getting rows with the same ID (although I can't think of a scenario where you would do this).

I couldn't say if it's best practise or not, but it certainly works.



回答5:

Yes If you delete a row say with id 7 the next value of auto increment will be 8 and not 7 again. So all the values will definitely be unique. and you will need to truncate the table to start the auto increment again. SO you can always use auto increment fields for user IDS.