Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random unique ID using PHP

I have a table that is looks like this. This is some of the general information when a user registers on my site.

+------------+------------+
|   user_id  | username   |
|   312543   |   Bobby    |
|   543765   |  Victoria  |
+------------+------------+

I am just wondering, how would you generate a random unique number for user_id? Let’s say a number between 1 and 100 that is not yet in the database. I want to accomplish this using PHP, not SQL.

like image 979
Bono Avatar asked Dec 01 '22 02:12

Bono


2 Answers

Improving upon Niet the Dark Absol's answer: You can use uniqid(rand()). uniqid() will generate a number based on your server's internal clock and rand() will prefix it with a random number. So even if two users register in the same tiniest fraction, the rand() prefix will assign them a different prefix with over 99.99999% probability.

like image 169
Crashh Avatar answered Dec 04 '22 04:12

Crashh


You could use PHP's uniqid function. It's not random (it's based on the server's clock) but unless you have two people register in the same tiniest fraction of a second then it will be guaranteed to be unique and it's non-sequential.

like image 34
Niet the Dark Absol Avatar answered Dec 04 '22 05:12

Niet the Dark Absol