Create a random token, check for a duplicate

lyncher

New Member
I have a php script that makes a random token (A-Z, a-z, 0-9):\[code\] function token($length) { $characters = array( "A","B","C","D","E","F","G","H","J","K","L","M", "N","P","Q","R","S","T","U","V","W","X","Y","Z", "a","b","c","d","e","f","g","h","i","j","k","m", "n","o","p","q","r","s","t","u","v","w","x","y","z", "1","2","3","4","5","6","7","8","9"); //make an "empty container" or array for our keys $keys = array(); //first count of $keys is empty so "1", remaining count is 1-6 = total 7 times while(count($keys) < $length) { //"0" because we use this to FIND ARRAY KEYS which has a 0 value //"-1" because were only concerned of number of keys which is 32 not 33 //count($characters) = 33 $x = mt_rand(0, count($characters)-1); if(!in_array($x, $keys)) { $keys[] = $x; } } foreach($keys as $key){ $random .= $characters[$key]; } return $random;\[/code\]} Works perfect, but I want to be able to check a certain database to make sure the same token has never been used before. And if it has it will instantly recreate a fresh token before outputing it.I know I can use this script to check for a duplicate:\[code\]$check = mysqli_query($mysqli, "SELECT ".$table.".token FROM ".$table." WHERE ".$table.".token = '".$random."'"); if(mysqli_num_rows($check) > 0){ //ERROR: DUPLICATE TOKEN, CREATE A NEW TOKEN NOW... }\[/code\]I just need help to add it all together, so that if a duplicate is found in the database, it will loop back and try again.
 
Back
Top