Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Generate Unique Order Number with Date

I want to generate unique identificator in following 12 numeric format:

YYYYMMDDXXXX

Example:

201403052318

Where:

YYYYMMDD is a current date value and other XXXX is randomly generated value.

$today = date("Ymd");
$rand = sprintf("%04d", rand(0,9999));
$unique = $today . $rand;

Daily required unique volume is about 100. What methods using PHP should I use to prevent possible duplicates in rand values or make all id maximum unique? Maybe possible use current time functions to compact these numbers in last 4 characters?

EDITED: Unique value connected to MySQL database as prime index of table. It is initial values not connected to any stored information in database.

like image 241
Ken Tang Avatar asked Mar 09 '14 06:03

Ken Tang


1 Answers

You can't rely on rand() , There is a possibility you will generate a duplicate (Pretty rare for a rand(0,9999) to generate a duplicate, but that will at some point).

So instead of going for rand(), just create an incremental value (say.. starting from 1) and append to your generated date.

Next time when you regenerate a new id, grab that incremental value's (say if you had stored it somewhere.. must be 1 right ?) status, increment it and append it to your new date.

Not an ideal solution.. (Critics welcome)

You can make use of a uniqid coupled with sha-1 and time and do a substr() on them for first 4 chars.

<?php
$today = date("Ymd");
$rand = strtoupper(substr(uniqid(sha1(time())),0,4));
echo $unique = $today . $rand;

OUTPUT :

201403094B3F
like image 58
Shankar Narayana Damodaran Avatar answered Sep 27 '22 20:09

Shankar Narayana Damodaran