سؤال

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?

هل كانت مفيدة؟

المحلول

Increment the last value by a random amount instead of using a random value. Like so:

$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);
}

Then convert the integer key to and from any format, say using base_convert.

نصائح أخرى

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

The best bet would be to make sure the image doesn't exist by using the random number generator against the list of images before writing a new image with that number in it.

Try to increase the amount and type of characters by using an algorithm that uses numbers, letters so it increases the combinations that you can have.

Did you try using mt_rand() http://www.php.net/manual/en/function.mt-rand.php. Also you should be increasing the range.

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

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top