I am trying to create a token as a user unique referral and so I used md5 to generate it. However, I heard that there is a possibility of duplication. Then, I tried to check the token before inserting it to the database every time when the token is generated in the following way.
- Select token_column from table where token_column != generated_token.
- If generated_token is exist, generate new and check the table again.
- If generated_token is not exist, insert it into the database.
Controller
private function generateToken(){
$token = strtoupper(md5(rand()));
$sql = 'SELECT id, token FROM UserReferral WHERE token != '.$token;
$is_exist = $this->Database_model->readOneQuery($sql);
if(!empty($is_exist)){
// Insert data into database
} else {
$token = strtoupper(md5(rand()));
// check database again to see if the token is already exist
}
}
Model
function readOneQuery($sql){
$r = $this->db->query($sql)->row_array();
return !empty($r) ? $r : false;
}
If I do this way, the checking seems no ending. Is there any better way I can use to do the data checking?