我正在尝试创建一个php函数,为mysql主键列生成唯一的大型int。 这是功能:
function createUniqueId()
{
$unique_id="";
if (function_exists('com_create_guid') === true)
{
$unique_id = com_create_guid();
}else
{
$unique_id = sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(16384, 20479), mt_rand(32768, 49151), mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535));
}
$unique_id = str_replace("-","",$unique_id);
$unique_id = str_replace("{","",$unique_id);
$unique_id = str_replace("}","",$unique_id);
$unique_id = strtolower($unique_id);
$unique_id = base64_encode(pack("h*",$unique_id));
$tmp= 1;
for($i = 0;$i<strlen($unique_id);$i++)
{
$t1 = substr($unique_id,$i,1);
$tmp = (bcmul((time()*microtime() )^ $tmp ^ ord($t1),2));
}
$unique_id = ($tmp);
$tmp = "";
$tm = time();
$ti = 0;
for($i = 0;$i<strlen($unique_id);$i++)
{
$t1 = substr($unique_id,$i,1);
$t2 = substr($tm,$ti,1);
$val = ord($t1) ^ ord($t2);
if($val == 0 && $tmp == "")
continue;
$tmp .= $val;
$ti = $ti+1>strlen($tm)-1?0:$ti+1;
}
$unique_id = ($tmp).(intval(microtime()*10) ^ time()).mt_rand(100,2000);
$unique_id = strlen($unique_id > 19)?substr($unique_id,0,19):$unique_id;
return $unique_id;
}
这是我做的测试(我已经尝试了很多次而没有任何重复的密钥,但我担心它会在某一天)。
for($j = 0;$j<10000 ;$j++)
{
$uid = createUniqueId();//e.g 2329590364151828804
echo ($j+1)." inserting new record with id = $uid <br>";
//then i add a new line to the table users
echo executeQuery("insert into Users values(?)",$uid,"db_test");
}
更新
我的想法是,我试图从GUID中获得一个独特的bigint。