What is the best way to generate random code that does not repeat in the database?

Asked

Viewed 3,707 times

1

I need to generate a random code of 5 characters, can not have repetitions. I managed to do as follows:

function testarcode($code){
    global $link;
    if ($code == ""){
        return false;
    }
    $comando = "SELECT * FROM tbl_usuario WHERE code='$code'";
    $query = mysqli_query($link, $comando);
    if(mysqli_num_rows($query) > 0){
        return false;
    }
    else{
        return true;
    }
}

function gerarcode(){
    $caracteres = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $max = strlen($caracteres) - 1;
    $code = "";
    while (testarcode($code) == false){
        for($i=0; $i < 5; $i++) {
            $code .= $caracteres[mt_rand(0, $max)];
        }
    }
    return $code;
}

Although it is working I found my code very dirty. There is some way to make it easier and/ or simplified?

It is not a duplicate of other questions because in this question a code is asked on PHP and others, in MySql.

  • maximum 5 characters?

  • It has to be 5 characters, no more, no less.

  • I’ve already added an answer.

  • 1

    If you want to make sure it doesn’t happen again, first set a type index UNIQUE in the field, then for each new generated code, make a query to see if it already exists, if it exists, generate a new code, otherwise record in the database.

  • Would it not be duplicated? https://answall.com/questions/222090/gera%C3%A7%C3%A3o-de-id-%C3%Banico-com-mysql

1 answer

3


you can use the uniqid function that returns a prefixed unique identifier based on current time in millionths of a second.

echo uniqid();
// Saida: 5975b4239b793

or you can also pass a parameter to the function uniqid, for example:

echo uniqid(rand());
// Saida: 103550780059754516d29da

To get the first 5 characters use the sbstr function()

echo substr(uniqid(rand()), 0, 5);
// Saida: 43395
  • Was unaware of this function uniqid(), thank you!

  • Good answer, just recommend checking if it is not repeated in the database before entering the data, because its maximum limit of combinations will be 376.992 due to its limitation of 5 characters, well less than uniqueid() itself can provide (5.3 undecilions)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.