vlady
vlady

Reputation: 600

Loop for random string

$new_random_string = substr(str_shuffle('0123456789'), 0, 2);

$strings = mysql_query("SELECT `string` FROM `table`");
while ($string = mysql_fetch_row($strings)) {

if ($new_random_string == $string[0]) 

// generate new random string

}

mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");

I want a loop to generate a new string in case it already exists in database. Thanks.

Upvotes: 0

Views: 229

Answers (4)

Riz
Riz

Reputation: 10246

do{

    $new_random_string = substr(str_shuffle('0123456789'), 0, 2);
    $string = mysql_query("SELECT `string` FROM `table` WHERE `string` = $new_random_string");
    $string = mysql_fetch_row($strings)

}while($new_random_string == $string[0]);

mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");

Upvotes: 0

FatalError
FatalError

Reputation: 964

function gen_string() {
   return substr(str_shuffle('0123456789'), 0, 2);
}

do {
$rand = gen_string();
$query = mysql_query("SELECT count(*) as rows FROM `table` where `string` ='".$rand ."'; ");

$row = mysql_fetch_row($query);

} while ($row['rows']>0);

mysql_query("INSERT INTO `table` (`string`) VALUES ('".$rand."')");

It is not tested but it should work.

Upvotes: 0

Ozerich
Ozerich

Reputation: 2000

while(1)
{
   // generate new random string
   if(mysql_result(mysql_query("SELECT COUNT(*) FROM `table` WHERE `string` ".$new_random_string), 0) == 0){
       mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");
       break;
   }
}

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838186

It looks like you are trying to generate random strings and insert them into the database, but with the restriction that there cannot be duplicates.

To ensure there cannot be duplicates the best approach is to create a UNIQUE index on that column. Then the database will ensure that there will never be a duplicate value.

To insert new values you can either query the database to see if your specific string exists already before inserting it. Or you can just go ahead and try to insert and see if it works - the UNIQUE constraint will prevent any duplicates from being inserted.

Upvotes: 1

Related Questions