0

I have a table that has an auto-increment "id". I have another column in the same table that has a "key", which I want to be based on the auto-increment "id". This will ensure that there is never a duplicate "key". I want to preferably have a 6 character unique id generator. I found this online, but I am open to other suggestions.

Mumbo Jumbo
  • 360
  • 1
  • 2
  • 12
  • check out this one : http://stackoverflow.com/questions/3954599/generate-random-string-from-4-to-8-characters-in-php – Thomas Ruiz Mar 10 '13 at 08:35

2 Answers2

0
echo $result['id'] . '_' . uniqid('', true);

this will produce something like 1_513c5858c04967.71142475, the prefix ID_ will be always unique based on the database ofcourse

isnt it unique enough?

ahh you want 6 characters, what about:

function randString($length, $charset='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')
{
    $str = '';
    $count = strlen($charset);
    while ($length--) {
        $str .= $charset[mt_rand(0, $count-1)];
    }

    return $str;
}

  $key = $result['id'] . '_' . randString(6); //this is unique, cause even you get at a chance of a million that you will get 2 same randString(6); you will have always unique prefix ID_ so you will have 1_G7owOq and 2_G7owOq

  //the code below is just an example of how to loop column for unique key and u dont need it :P just maybe someone else needs it.
  while(mysqli_num_rows(mysqli_query($con, "SELECT id FROM table WHERE key = '".mysqli_real_escape_string($con, $key)."'")) > 0) { 
    $key = $result['id'] . '_' . randString(6); 
  }
Wiggler Jtag
  • 669
  • 8
  • 23
  • Is it possible to create the "key" to have just 6 chars only (in total). If the rows become too high..I might land up with something like 345000_aeRfTG otherwise. Can you please tell how do I achieve this? – Mumbo Jumbo Mar 11 '13 at 06:54
0

Then there is the last way i posted you here:

$key = randString(6);
while(mysqli_num_rows(mysqli_query($con, "SELECT id FROM table WHERE key = '".mysqli_real_escape_string($con, $key)."'")) > 0) { 
    $key = randString(6); 
}

It will always create random 6 char key, because if it hits already existing key in db, it will re-create new one and so on, until its unique:] It is the best way for u, this way I'm also using :]

Actually the best-best way would be to generate table with all existing unique keys (62^6) * 6 bytes each key -> 317 GB if I'm not mistaken (morning) :] I dont think you will hit 1/10000 of that :]

Wiggler Jtag
  • 669
  • 8
  • 23