I want to generate the sequence of number starting from 000001 (total six digits) with the prefix of the current year. And then store it into the database. The format will be like this: year-000001.
For example: 2016-000001
And when the year will changed then the sequence of number will automatically reset to 000001.
For example: 2017-000001
By using date()
and str_pad()
you can generate the sequence like 2016-000001
$year= date('Y');
$year=$year.'-';
$n=0;
$n = str_pad($n + 1, 6, 0, STR_PAD_LEFT);
$number=$year.$n;
echo $number;
If you have retrieved the last assigned number from the database, and need to generate the next in PHP, you can use this function:
function getNextNumber($id = '') {
$year = date('Y');
$seq = $year <> +$id ? 0 : +substr($id, -6);
return sprintf("%0+4u-%0+6u", $year, $seq+1);
}
// Example calls (in 2016):
$id = getNextNumber('2016-023000'); // 2016-023001
$id = getNextNumber('2015-193481'); // 2016-000001
The first time, you just pass the empty string, or nothing at all:
$id = getNextNumber(); // 2016-000001