Generate a random while there is no equal one in the db

0

Good afternoon I have the following code to generate a sequence of letters and numbers.

function aleatorio($longitud, $tipo=0){
    $codigo = "";
    $caracteres="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    $max=strlen($caracteres)-1;
    for($i=0;$i < $longitud;$i++)
    {
        $codigo.=$caracteres[rand(0,$max)];
    }
    return $codigo;
}

and I call the function to give me a random.

My new problem is that I need to create a random one and check that it does not exist in the database and I do not know how to do it, the idea is that it is a unique random in the database.

    
asked by Mauricio Delgado 23.08.2018 в 21:06
source

1 answer

0

This works for you, you just have to adapt it to your table in the database

function token()
{
    $token = md5(uniqid(rand(),true));
    return $token;
}

This function creates you random numbers you can call it when you are saving in the database and to make the comparison with existing records

$token = token();

Here you make the call to the function to which you will be able to manipulate it in your PHP to make the respective comparisons

$sql = "SELECT tu_campo_aleatorio FROM tu_table WHERE tu_campo_aleatorio = '".$token."'";

Your query in the database to verify if that code already exists

And finally ...

if($sql == TRUE)
{
    //Tu código
    echo "Ya existe este código en la base de datos";

}else{

    //Tu código
    echo "Puedes utilizar este código";
}

You return the result obtained.

    
answered by 23.08.2018 / 23:36
source