Reputation: 212
I have dilemma. I need unique string in my database table to show it in url (I don't show id in url).
I want generate in php unique string check it is unique in table if not generate new.
What do you think in terms of performance for a string with a length of 8 characters, and with a large number of rows (about 100,000 rows).
Upvotes: 0
Views: 58
Reputation: 116100
Instead of generating a unique key besides the id, you can also create a function that hashes or encodes the id to a string. For instance, you can convert the integer to an 8 character hexidecimal representation. You can make it a little more complex if you like, but still, it's fairly easy to write a function that uses a fixed formula to convert a number to 8 letters and vice versa. That way, you don't need to store this extra data, and you don't have to worry about the value being unique.
<?php
function translate($key, $back)
{
$key = str_pad($key, 8, '0', STR_PAD_LEFT);
$a = array('1','2','3','4','5','6','7','8','9','0');
$b = array('a','b','c','d','e','f','g','h','i','j');
if ($back) {$c = $b; $b = $a; $a = $c;}
return str_replace($a, $b, $key);
}
function encode_id($int)
{
return translate($int, false);
}
function decode_id($key)
{
return (int)translate($key, true);
}
$key = encode_id(40000);
$int = decode_id($key);
echo $key;
echo '<br>';
echo $int;
Upvotes: 1
Reputation: 42440
You can create a unique id in php using uniqid()
.
When generating a new ID, check the DB to see if it exists. If it does, create a new one. Assuming you set up an index on that column in the database, these checks will not be very expensive.
In pseudo(-ish) code :
while (true) {
$id = uniqid();
if (!id_exists_in_db($id)) // we have a unique id
break;
}
Upvotes: 1