SQL & PHP 唯一编号

SQL & PHP Unique Number

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

TOM05543
TOM04423
KEL04432
KAL43242

执行此操作并事先用这些唯一 ID 填充我的数据库的最佳方法是什么?

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

中插入唯一生成的记录
<?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 的机会大约是 2^122 分之一,这意味着如果你每 1 毫秒生成一个 GUID,你会命中大约 10^26 年来的第一次重复。

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