0

I have a service on the internet where people post pictures and a short string is generated. Only one can be used ever. However, I am getting into duplicates in the database and I am seeing major problems.

Here's what I am using:

$id=rand(10000,99999);
$short_string = base_convert($id,20,36);

What would be the best way to fix it? Check from the database and keep looping till it doesn't match one? What if every possible solution and it goes in an infinite loop?

4

5 回答 5

1

Put your PK through an algorithm that generates a unique number from it and put that through your function.

于 2011-05-21T01:41:52.360 回答
1

最好的办法是在写入包含该数字的新图像之前,通过对图像列表使用随机数生成器来确保图像不存在。

尝试通过使用数字、字母的算法来增加字符的数量和类型,从而增加您可以拥有的组合。

于 2011-05-21T01:46:10.800 回答
1

将最后一个值增加一个随机量,而不是使用随机值。像这样:

$results = mysql_query("SELECT * FROM thetable ORDER BY theId DESC LIMIT 1");
$keyToUse = 1;
if($row = mysql_fetch_array($results)) {
    $keyToUse = (int)$row['theId'] + rand(1, 100);
}

然后将整数键转换为任何格式,例如使用base_convert.

于 2011-05-21T02:05:39.877 回答
1

您是否尝试过使用mt_rand() http://www.php.net/manual/en/function.mt-rand.php。你也应该增加范围。

于 2011-05-21T02:14:09.143 回答
0

Use md5 http://php.net/manual/en/function.md5.php The strings produced have no conflict (with large probability).

于 2011-05-21T01:40:31.230 回答