I have develop this function which uses recursion to call itself. I need to generate a unique activation code.
It goes like this:
1. A random string is generated using the function in seperate class file. (See 2nd Code)
2. I am checking for uniqueness of that string in the activation table so that there are no duplicates.
3. In case if the random string is re-generated though I know that the chances are very less, but I dont want to take any chances. So I am checking it against the table records.
If the generated activated code is already there, then function should call itself again to generate a new activate code and the whole process goes on till we get a unique activation code which doesnt exist in the table records.
My question is that, Have I coded it correctly i.e. the recursion part. Please let me know if its not correct or if anybody has better or effective way to achieve this.
Note: I am calling these functions from a class file. Simply speaking I am using OOPs.
So I need to know the code to call the recursion should be
return generateUniqueActivationCode();
or
return $this->generateUniqueActivationCode();
Any help will be highly appreciated.
// Generate Unique Activation Code
//*********************************************************************************
public function generateUniqueActivationCode()
{
$mysql = new Mysql();
$string = new String();
// This is coming from the 2nd part of code snippet that I have added
$activation_code = $string->generateActivationCode();
// Is Activation Code Unique Check
$sql = "SELECT activation_id FROM ". TABLE_ACTIVATION_CODES ." WHERE activation_code='$activation_code' LIMIT 1";
$query = $mysql->query($sql);
if($mysql->rowCount($query) > 0)
{
// This function is calling itself recursively
return generateUniqueActivationCode();
}
else
{
return $activation_code;
}
}
This is the code for generating Random Activation code
class String
{
// Generates A Random String (Can be used for generating password etc.)
//*********************************************************************************
public function generateRandomString($noofchars=8)
{
$salt = "ABCDEFGHIJKLMNOPQRSTUVWXYZabchefghjkmnpqrstuvwxyz0123456789";
srand((double)microtime()*1000000);
$i = 0;
while ($i <= $noofchars)
{
$num = rand() % 33;
$tmp = substr($salt, $num, 1);
$string = $string . $tmp;
$i++;
}
return $string;
}
}
?>
I would have typed it like this:
Do (that runs ATLEAST one time), but repeats as long as your rowCount returns something bigger than 0.