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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With