Unique id with Preferred string
Posted: Sun Aug 20, 2006 3:47 pm
I was without Internet for some hours due to thunderstorm so i made this. Id like for the pros to comment and suggest on it, so i might learn something.
Thanks!
Thanks!
Code: Select all
function generate_id($tablename, $pref_id = 'Unsuplied') {
# (Uses fetch_query function)
# Create unique id (and random) for given DB-table. Tables are fixed, all have first field as varchar of lenght 20
# We use the pref_id as far as possible for its easier to spot real string from the database
# We use suffix of random characters separated from the string with _
# $tablename # Table in database we create for
# $pref_id # The string we use basis for the id, PREFix or PREFferred
# Find out the id-fields name (and lenght)
$name_query = fetch_query("Describe $tablename");
$name_line = mysql_fetch_array($name_query, MYSQL_ASSOC); # Its on the first row since id is first field
$idfield_name = $name_line['Field'];
#$id_lenght = $name_line['Field']; # returns: varchar(xx)
#$id_lenght = str_replace('varchar(', '', $idfield_lenght);
#$id_lenght = trim(str_replace(')', '', $idfield_lenght));
$id_lenght = 20; # Desired lenght of the id
$pref_lenght = min(20, strlen($pref_id)); # Lenght for the pref_id
# Loop while some part of pref_id remains, otherwise give up
while($pref_lenght > 4) {
# Calculate lenght for suffix
$suffix_lenght = $id_lenght - $pref_lenght; # Lenght for the suffix
# Loop 10 times, if not unique found, decrease pref_lengh
for ($i = 0; $i < 10; $i++) {
# Generate new id, with random suffix with leading _
if($suffix_lenght > 0) {
$tmp_suf = random_id($suffix_lenght);
$tmp_suf[0] = '_';
}
else
$tmp_suf = '';
$tmp_id = substr($pref_id, 0, $pref_lenght) . $tmp_suf;
# Compare to database
$tmp_query = fetch_query("SELECT * FROM $tablename WHERE $idfield_name='$tmp_id' ");
# If no matching lines, unique id is returned
if(mysql_num_rows($tmp_query)==0)
return $tmp_id;
# If more than 1 line found, notify user and stop
if(mysql_num_rows($tmp_query)>1)
exit("Multiple unique ID's found!!!");
# If we came here, its time to try again
}
# No luck with the 10 tries, lets shorten the pref
$pref_lenght = $pref_lenght - 1;
}
# If we came here, no ID was generated
return false;
}
function random_id($len){
$id = "";
for ($i = 1; $i <= $len; $i++){
mt_srand(make_seed()+$i);
$num=mt_rand(0, 2);
if ($num==0)
$randval = mt_rand(48, 57);
elseif ($num==1)
$randval = mt_rand(65, 90);
else
$randval = mt_rand(97, 122);
$id.=chr($randval);
}
return($id);
}
function make_seed(){
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}