Jump to content

[SOLVED] generate random string that isn't already in DB


BandonRandon

Recommended Posts

Hello,

 

I have found many functions that generate random strings i am currently using one that works well. But here is a potential problem I would like to stop before it happens. I'm inserting the random string into a db and need it to be unique if the string exist I need it to create another one. Here is the random string code:

 

function genRandomString() {
    $length = 5;
    $characters = '023456789abcdefghijkmnopqrstuvwxyz';
    $string = '';    

    for ($p = 0; $p < $length; $p++) {
        $string .= $characters[mt_rand(0, strlen($characters))];
    }
    return $string;
}

 

which works great. However, when I insert it in the DB i need to make sure that a string that looks like that doesn't already exist (sure there are  45435424 combination but just to make sure) What i have now will check the current generated string and if its in the DB make a new one. I would assume that if the new string is in the DB this code wouldn't check that. I think i need to loop to the code somehow and say if "new string == randomstring" then try again. Any help on this would be great.

 

Here is the db code.

 

	//generate random string
			$random_string = $this->genRandomString();
			//select all random strings from the database
			$check_random_string_q = 'SELECT rand_string FROM '.URL_TABLE.' WHERE (rand_string="'.$random_string.'")';
			$check_random_string_result = mysql_query($check_random_string_q);
			$check_random_string_row = mysql_fetch_array($check_random_string_result);
			//if the string is in the database generate a new one				
			if($random_string == $check_random_string_row['rand_string']){
			$random_string = $this->genRandomString();
			}

			$q = 'INSERT INTO '.URL_TABLE.' (url, rand_string, date) VALUES ("'.$url.'","'.$random_string.'", NOW())';

 

Thank you!

Brooke

Link to comment
Share on other sites

so, you can always put it in a do/while loop to keep generating a string and testing with a SELECT...but there are probably better solutions. can you elaborate on what you are trying to do and what parts are set in stone? if you are just looking for a unique id for a record, most DBs have some sort of auto_increment functionality to give each record a unique id. if you don't want that, can the length be increased? if so, i have another alternative

Link to comment
Share on other sites

Thanks rhodesa,

 

What I am trying to do is re-write parts of an open source tinyurl application. Each link in the database is already assigned a unique id but what i need to do is also assign it a unique "string" for example if someone goes to site.com/a1b3c it will go into the database find the row with the rand string matching "a1b3c" and then redirect to that url. All that is working fine. but because I'm using a function to generate the random string I need to make sure that it's unique. That way 2 links can't both have the rand_sting of "a1b3c" as that would only link to the most recent url with that rand_string.

 

I hope that is a little bit clearer. I was thinking of doing a do/while loops but i get confused when it comes to loops :)

 

Brooke 

Link to comment
Share on other sites

then...

 

I guess you would do this (to keep the function you have)

 

1. Turn the rand_string column to unique

 

2. do an insert into the database, it will insert if it isn't in the database, otherwise it won't.

 

3. after the insert, use mysql_affected_rows, if you get 1, the insert was successfully otherwise, create a new random number.

Link to comment
Share on other sites

The Little Guy, to get a really unique string, use:

microtime(true).getmypid();

...feel free to md5() that if you so desire :)

 

BandonRandon, as TLG said, you can add a UNIQUE attribute to the 'rand_string' column, or just run a SELECT to test it. It's up to you, but the SELECT method (since you are already on that track) would look like:

 

do {
  $random_string = $this->genRandomString();
} while (mysql_num_rows(mysql_query("SELECT rand_string FROM ".URL_TABLE." WHERE rand_string='{$random_string}'")));
$q = "INSERT INTO ".URL_TABLE." (url, rand_string, date) VALUES ('{$url}','{$random_string}', NOW())";
$result = mysql_query($q);

Link to comment
Share on other sites

don't forget the random string line:

 

do {
   $random_string = $this->genRandomString();
   $q = "INSERT INTO ".URL_TABLE." (url, rand_string, date) VALUES ('{$url}','{$random_string}', NOW())";
   $result = mysql_query($q);
} while (mysql_affected_rows($result) < 1);

 

edit: and the $result in mysql_affected_rows()

 

Link to comment
Share on other sites

don't forget the random string line:

 

do {
   $random_string = $this->genRandomString();
   $q = "INSERT INTO ".URL_TABLE." (url, rand_string, date) VALUES ('{$url}','{$random_string}', NOW())";
   $result = mysql_query($q);
} while (mysql_affected_rows($result) < 1);

 

edit: and the $result in mysql_affected_rows()

 

 

Oops forgot the random string... but $result is optional, but it is a good thing to add.

Link to comment
Share on other sites

Thank you both very much for your help. I was able to do it using rhodesa original way of:

do {
  $random_string = $this->genRandomString();
} while (mysql_num_rows(mysql_query("SELECT rand_string FROM ".URL_TABLE." WHERE rand_string='{$random_string}'")));
$q = "INSERT INTO ".URL_TABLE." (url, rand_string, date) VALUES ('{$url}','{$random_string}', NOW())";
$result = mysql_query($q);

 

The second way created an infinite loop, I may try the alternative method again later.

 

Thanks again,

Brooke

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.