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?
– RFL
It has to be 5 characters, no more, no less.
– Francisco
I’ve already added an answer.
– RFL
If you want to make sure it doesn’t happen again, first set a type index
UNIQUEin 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.– gato
Would it not be duplicated? https://answall.com/questions/222090/gera%C3%A7%C3%A3o-de-id-%C3%Banico-com-mysql
– Inkeliz