Php 为了获得唯一的4个字符的ID,可以使用包含SQL的递归方法吗?

Php 为了获得唯一的4个字符的ID,可以使用包含SQL的递归方法吗?,php,mysql,recursion,Php,Mysql,Recursion,我有一个PHP/MySQL电子商务网站,需要4个字符的订单ID。使用这样的递归方法可以吗: private function getOrderId() { $chars = '0123456789abcdefghijklmnopqrstuvwxyz'; $num_chars = strlen($chars); $id_len = 4; $candidate_id = ''; for($i = 0; $i < $id_len; ++$i) {

我有一个PHP/MySQL电子商务网站,需要4个字符的订单ID。使用这样的递归方法可以吗:

private function getOrderId() {
    $chars = '0123456789abcdefghijklmnopqrstuvwxyz';
    $num_chars = strlen($chars);
    $id_len = 4;
    $candidate_id = '';

    for($i = 0; $i < $id_len; ++$i) {
        $candidate_id .= $chars[mt_rand(0, $num_chars - 1)];
    }

    // check if $candidate_id exists using MySQL

    //
    if($it_exists) {
        return $this->getOrderId();
    }
    else {
        return $candidate_id;
    }
}
私有函数getOrderId(){
$chars='0123456789abcdefghijklmnopqrstuvwxyz';
$num_chars=strlen($chars);
$id_len=4;
$candidate_id='';
对于($i=0;$i<$id\u len;++$i){
$candidate_id.=$chars[mt_rand(0,$num_chars-1)];
}
//使用MySQL检查$candidate_id是否存在
//
如果($it\u存在){
返回$this->getOrderId();
}
否则{
返回$candidate\u id;
}
}

< /代码>递归给你买什么,一个正常的循环没有?考虑使用<代码>插入忽略< /代码>,而不是用<代码>检查> >选择< /代码>。当前用户仍有可能在(几乎)相同的时间获取完全相同的ID。