user248289
user248289

Reputation:

PHP: How To Create a Unique #

I've seen lots 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)

Upvotes: 1

Views: 2124

Answers (4)

Corey Ballou
Corey Ballou

Reputation: 43457

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.

Upvotes: 0

Ian
Ian

Reputation: 25336

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.

Upvotes: 0

Eric Mickelsen
Eric Mickelsen

Reputation: 10377

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

hexdec(uniqid())

Upvotes: 1

ryeguy
ryeguy

Reputation: 66851

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.

Upvotes: 3

Related Questions