开发者

Create random string, check if it exists, if it does create a new one

I want to generate a random string of about 5 characters long. I can create it ok, but I'm having trouble checking if it exists in an array (or database in real situation) and creating a new one if it does.

I use a function like this to generate the string:

function rand_string(){
    return substr(md5(microtime()), 0, 5)开发者_如何学Go;
}

But them I'm lost.

  • I need to check if it exists already.
  • If it does, make a new one
  • And repeat


Try this:

function rand_string(){
    $str = substr(md5(microtime()), 0, 5);
    if(exists_in_db($str)) $str = rand_string();
    return $str;
}


Just a warning that if you are using this to generate a unique string by adding it to the database once you've determined it's not been used then this is not safe in a concurrent environment.

In the interval between you checking it's not in the database, and adding a record containing it later on another thread could do the same...

If you are using it this way, probably the safest approach is to ensure that the field containing the string has a unique constraint on it and try to add it. If you suceeded in adding it then you know it was unique, if you didn't then it wasn't. And this is safe to do in a multithreaded environment.

If you are simply checking against a static list of strings and do not intend to add the generated string to the database then ignore this post :P


To check if it's in the DB run a query after.

$unique=FALSE;
    while(!$unique)
      {
      $str = substr(md5(microtime()), 0, 5);
      //Insert SQL Code to check if used here
      if($row['ID']=='')
          $unique=TRUE;
      }


on a database you could..:

select substr(newid(),1,5) as name

for a new string and to check..:

select count(*) as cnt from yourtable where yourcolumn = __GENERATED_string__

build a while around it and you'Re done


With the mysql_query(), use a select statement to see if you return any results (i.e., "Select * from table where col1 = 'String'". Then test to see if any rows were returned. Loop through these calls until you have a truly random, unused value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜