2016-09-06 68 views
0

我將使用與NFC GET方法去拉一些數據,我想填充一噸的唯一數字的數據庫,我不介意他們有像SQL和PHP唯一編號

TOM05543 
TOM04423 
KEL04432 
KAL43242 
在他們的關鍵字

什麼是最好的方法做到這一點,並用這些獨特的ID填充我的數據庫之前?

+1

不是自動遞增的值適合你嗎? – apokryfos

+0

@apokryfos我希望這些數字是獨一無二的,不容易被猜到,讓它們安全,因爲它不會保存敏感數據並不是最重要的。我只是想它的方式,它不是1,2,3,4,5,6等...還保持他們短,並添加關鍵字來填充大量的唯一ID's – NathanK

+0

你有沒有嘗試過或想要的代碼由SO用戶。 –

回答

1

創建一個PHP函數,它可以生成一個隨機的apha數字代碼並檢查數據庫表中是否存在代碼。如果存在,則遞歸調用函數直到生成唯一代碼。並在數據庫表中插入唯一生成的記錄。

<?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); 
} 
?> 
+0

太棒了!謝謝拉胡爾。 – NathanK

+0

@NathanK歡迎您。 –

+0

好的答案,但選擇的隨機字符串需要引用。這會引發語法錯誤。 –

0

您可以使用在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是不是技術上獨有的,但是一個好的隨機數發生器產生兩個相同的GUID的機會大約是1^2^122,這意味着如果每1毫秒產生一個GUID,那麼在10^26年左右就會產生第一個副本。

這樣做的好處是不需要檢查數據庫,如果密鑰已經存在或沒有,因爲我們假設它不是。