简体   繁体   中英

How can I generate a random and unique id based on the current table row using PHP and MySQL?

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.

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

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 :]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM