SQL和;PHP唯一编号


SQL & PHP Unique Number

我将使用NFC的GET方法来提取一些数据,我想用大量的唯一数字填充数据库,我不介意它们中有关键字,如

TOM05543
TOM04423
KEL04432
KAL43242

在此之前用这些唯一的ID填充我的数据库的最佳方法是什么?

创建一个PHP函数,它可以生成一个随机的apha数字代码,并检查代码是否存在于DB表中。如果存在,则递归调用函数,直到生成唯一的代码。并在DB表中插入唯一生成的记录。

<?php
//DB connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");
//Function to generate unique alpha numeric code
function generateRandomNumer($con,$len=8){
    $randomString = substr(MD5(time()),$len);
    //Check newly generated Code exist in DB table or not.
    $query = "select * from table_name where col_name='".$randomString."'";
    $result=mysqli_query($con,$query);
    $resultCount=mysqli_num_rows($result);
    if($resultCount>0){
        //IF code is already exist then function will call it self until unique code has been generated and inserted in Db.
        generateRandomNumer($con);
    }else{
        //Unique generated code will be inserted in DB.
        mysqli_query($con,"INSERT INTO Persons (col_name) VALUES ('".$randomString."')");
    }
}
//Loop to insert number of unique code in DB.
//NUM_OF_RECORD_YOU_WANT_TO_INSERT define constant which contain number of unique codes you wants to insert in DB. 
for($i=0;$i<NUM_OF_RECORD_YOU_WANT_TO_INSERT;$i++){
    generateRandomNumer($con);
}
?>

您可以使用http://guid.us/GUID/PHP提供的解决方案,即:

function getGUID(){
    if (function_exists('com_create_guid')){
        return com_create_guid();
    }else{
        mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = chr(123)// "{"
            .substr($charid, 0, 8).$hyphen
            .substr($charid, 8, 4).$hyphen
            .substr($charid,12, 4).$hyphen
            .substr($charid,16, 4).$hyphen
            .substr($charid,20,12)
            .chr(125);// "}"
        return $uuid;
    }
}

关于guid的更多信息,请访问https://en.wikipedia.org/wiki/Globally_unique_identifier

我确实意识到GUID在技术上不是唯一的,但是一个好的随机数生成器生成2个相同GUID的机会大约是1/2^122,这意味着如果你每1毫秒生成一个GUID,你会在大约10^26年内遇到第一个重复的GUID。

这样做的好处是不需要检查数据库中键是否已经存在,因为我们假设它不存在。