0
$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.

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your contribution :)
0
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.

1 Comment

p.s. Make sure the gen_string has the ability to generate more than enough random strings you need, because if all the random string gets inserted in the table. You will have an infinite loop. length of 2 looks very small.
0
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;
   }
}

1 Comment

Thank you for your contribution to my question :)
0
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."')");

1 Comment

Thank you for your contribution to my question. I solved the problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.