I want to create unique id in my project. I have used this
$key = md5(microtime().rand());
But I want to create unique id like this : HPSEMP001
and so on HPSEMP002
,HPSEMP003
.
I am unable to do this please help me I am new in PHP
I want to create unique id in my project. I have used this
$key = md5(microtime().rand());
But I want to create unique id like this : HPSEMP001
and so on HPSEMP002
,HPSEMP003
.
I am unable to do this please help me I am new in PHP
You can create recursive function for generate random number, which is also checked in database if number is available in database or not.
In my example i have created different random departmentCode for customers using below code,
/**
* Generate Random number and check if it is exist or not
*/
public function checkAndGenerateRandomNumber($customerId) {
$number = sprintf("%04s", rand(1,9999));
$response = ClassRegistry::init('Department')->find('first', array('conditions' => array('Department.customer_id' => $customerId, 'Department.code' => $number)));
if(isset($response) && !empty($response)) {
$this->checkAndGenerateRandomNumber($customerId);
} else {
return $number;
}
}
I am a beginner, but I've tried this and it works:
$num = 0;
global $num;
function new_id() {
global $num;
return 'HPSEMP' . sprintf("%03d", $num++);
}
Example of calling the function:
for ($i = 0; $i < 1500; $i++) {
$new_id = new_id();
echo "<br>$new_id";
}
Output:
HPSEMP000
HPSEMP001
HPSEMP002
HPSEMP003
.
.
.
HPSEMP997
HPSEMP998
HPSEMP999
HPSEMP1000
Alternatively, if you would like to save the code in a database or file, I have not tried this but it should work:
function new_id($num) {
$num++;
// * Code to save new number value in file or database
return 'HPSEMP' . sprintf("%03d", $num++);
}
// * Code to retrieve id number from file or database and store it to $num
// * $num = previously stored id number
$new_id = new_id($num);