使用PHP生成随机的唯一ID [英] Generate a random unique ID using PHP

查看:121
本文介绍了使用PHP生成随机的唯一ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的表.这是用户在我的网站上注册时的一些常规信息.

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  |
+------------+------------+

我只是想知道,您如何为user_id生成一个随机的唯一数字?假设数据库中还没有一个介于1到100之间的数字.我想使用PHP而不是SQL来完成此操作.

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.

推荐答案

在黑暗骑士尼特(Niet)的基础上改善答案:您可以使用uniqid(rand()). uniqid()将根据您服务器的内部时钟生成一个数字,而rand()将为其添加一个随机数作为前缀.因此,即使两个用户以相同的最小分数进行注册,rand()前缀也将为他们分配不同的前缀,概率超过99.99999%.

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.

这篇关于使用PHP生成随机的唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆