开发者

PHP: How To Create a Unique #

I've seen lots开发者_如何学Go of examples of how to use uniqid() in PHP to create a unique string, but need to create a unique order number (integers only, no letters).

I liked the idea of uniqid() because from what I understand it uses date/time, so the chances of having another id created that is identical is nil.... (if I'm understanding the function correctly)


mt_rand should do the trick.

It generates a random number between its first paramater and its second paramater. For example, to generate a random number between 500 and 1000, you'd do:

$number = mt_rand(500,1000);

But if you're using it as an order number, you should just use an autoincrement column. Not only is that what it's there for, but what would you do in the event where the same number was generated more than once? Assuming you're using MySQL, you can read about autoincrement columns here.


Use hexdec to convert the hex string to a number. http://us.php.net/manual/en/function.hexdec.php

hexdec(uniqid())


uniqid() does what you're thinking it does.. but if you're plugging this value into a database, you're better off using an auto incrementing field for ids.. it really depends on what you're using the ids for.


I personally use date('U') to generate a string based on the number of seconds since the UNIX EPOCH. If this isn't random enough (if you think you're going to have two orders being placed within the same exact second) simply add another layer with mt_rand(0,9):

$uniqid = date('U') . mt_rand(0,9);

This will, in almost all cases, give you an incremental ID except for the case of having orders created at exactly the same second, in which case the second order could precede the first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜