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
.