What is the best way to generate random code that is not repeated in the database? [duplicate]

1

I need to generate a random 5 character code, can not have repetitions. I was able to do it 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's working, I found my code pretty piggy. Is there any way to do it more easily and / or simplified?

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

    
asked by anonymous 24.07.2017 / 02:33

1 answer

3

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

echo uniqid();
// Saida: 5975b4239b793

or you can also pass a parameter to the uniqid function, 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
    
24.07.2017 / 02:54