Question

How do generate unique serial or order number in php without checking against db?

Was it helpful?

Solution

see uniqid or uuid_create in uuid pecl or com_create_guid()

OTHER TIPS

If you want to guarantee uniqueness then you have to check against something. You could use a flat file and store just the most recently used number (which you can then increment), but it would be silly not to use a database. You need to store a bunch of other information linked to the number (contact details, what the order consists of, etc) and a database is ideal for that.

There are several issues using autoincrement columns in mysql (not least the fact that it does not scale to equivalent nodes).

While you can maintain a sequence generator just about anywhere (memcache, files, database) PHP does not implmenet sophisticated file locking semantics - in addition to affecting performance you can quickly get into deal-lock situations. It doesn't scale to large volumes.

If you've got PL/SQL available, then I'd recommend implementing a sequence generator there - alternatively you might consider implementing a generator in PHP and sqlite.

I would strongly recommend that you implement your generator to create numbers of format:

$use_number = ++$sequence_number . str_pad($node_id, '0', $max_nodes, STR_PAD_LEFT);

Where node_id is a number uniquely referencing the storage substrate where the current sequence number is stored. And $max_nodes is somewhat more than the the max number of digits found in $node_id (e.g. 3 would allow up to 999 nodes).

Alternatively treat it as a string with punctuation between the 2 parts (and/or store the 2 parts in different database columns).

C.

If you are using a MySQL database, you can generate a serial order number without needing to pre-check the database by using an auto_increment column. Inserting a new row will cause a new, unique ID to be assigned to that column without having to read/write that column in your PHP.

Alternatively, if you want a globally unique ID without even a database, then you could use PHP's uniqid() function. Note that this returns a string. If you use more than one physical machine or move between servers you should add a prefix (first argument) that is different on every machine. When used on the same machine, this function should never return the same string value twice.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top