我在想是否有人知道一种好的方法来为表的主键创建一个唯一的随机整数id。我正在使用MySQL。该值必须为整数。
我在想是否有人知道一种好的方法来为表的主键创建一个唯一的随机整数id。我正在使用MySQL。该值必须为整数。
如果你的目标是安全性,那么即使使用“随机”生成的数字,也不要使用Base62。
更好的选择是:
AUTO_INCREMENT
如果你愿意接受建议并且可以实现它,使用 UUID。MySQL 的 UUID()
函数将返回一个 36 个字符的值,可用于 ID。
如果你想使用整数,那么我认为你需要创建一个函数 getRandID()
,在 INSERT
语句中使用它。该函数需要使用随机数和现有 ID 的检查来返回一个之前未被使用过的 ID。
检查 MySQL 的 RAND()
函数。
AUTO_INCREMENT
,但向用户提供加密版本:SELECT HEX(AES_ENCRYPT(id,'my-private-key'));
id:SELECT AES_DECRYPT(UNHEX(encrypted_id),'my-private-key');
PHP
和MySQL
):
简短
数字
用于用户ID (唯一)
数字
插入行作为用户ID
看起来很复杂?继续阅读。
长:
表格:
users (user_id int UNIQUE)
代码:
<?php
// values stored in configuration
$min = 1;
$max = 1000000;
$numberOfLoops = 0;
do {
$randomNumber = rand($min, $max);
// the very insert
$insertedRows = insert_to_table(
'INSERT INTO foo_table (user_id) VALUES (:number)',
array(
':number' => $randomNumber
));
$numberOfLoops++;
// the magic
if (!isset($reported) && $numberOfLoops / 10 > 0.5) {
/**
* We can assume that at least 50% of numbers
* are already in use, so increment values of
* $min and $max in configuration.
*/
report_this_fact();
$reported = true;
} while ($insertedRows < 1);
$min
,$max
,0.5
)只是为了说明而存在,并没有统计意义。insert_to_table
和report_this_fact
函数不是内置于PHP中。它们也只是为了解释清楚而作为数字提供。我的方法适用于32位和64位平台。结果是64位。
function hexstr2decstr($hexstr){
$bigint = gmp_init($hexstr, 16);
$bigint_string = gmp_strval($bigint);
return $bigint_string;
}
function generate_64bitid(){
return substr(md5(uniqid(rand(), true)), 16, 16);
}
function dbGetUniqueXXXId(){
for($i = 0; $i < 10; $i++){
$decstr = hexstr2decstr(generate_64bitid());
//check duplicate for mysql.tablexxx
if($dup == false){
return $decstr;
}
}
return false;
}
AUTO_INCREMENT
? - RobertPitt