简体   繁体   中英

Generate unique id 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM