Create a random string, check if it exists if it creates a new one

I want to create a random string about 5 characters long. I can create it normally, but I have problems checking if it exists in the array (or in a real database) and when creating a new one.

I use a function like this to generate a string:

function rand_string(){
    return substr(md5(microtime()), 0, 5);
}

But I lost them.

  • I need to check if it already exists.
  • If so, make a new one.
  • And repeat
+3
source share
5 answers

Try the following:

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

, , , , , .

, , , , , ...

, , , , , . , , , , . .

, : P

+4

, .

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

in a database that you could:

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

for a new line and for checking ..:

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

create time around him and you will do

0
source

Using mysql_query (), use the select statement to see if you returned any results (ie, “Select * from the table, where col1 =" String ". Then check to see if the rows were returned. Until you have truly random, unused value.

0
source

Source: https://habr.com/ru/post/1758435/


All Articles