1

I'm attempting to create a PHP script that will create a random code and check it against a database to see if it exists. I'd like it to check that if it exists then generate another createRandomCode() and check it.

Unsure how to proceed with looping until the number of rows are 0.

function createRandomCode($length='6'){ 
    $chars = "abcdefghijkmnopqrstuvwxyz023456789"; 
    srand((double)microtime()*1000000); 
    $i = 0; 
    $code= ''; 
    while ($i++ < $length){ 
        $code = $code. substr($chars, rand() % 33, 1);  
    } 
    return $code; 
}

$shorturl = createRandomCode();

$q = $db - > query("SELECT * FROM maps WHERE url='".$shorturl.
    "'");
if (mysqli_num_rows($q) > 0) {

    $arr = json_encode($arr);
    echo $arr;
}
1
  • Please also read up about race conditions. Commented May 2, 2015 at 22:30

2 Answers 2

6

Sounds like a good candidate for a do...while loop:

do {
    $shorturl = createRandomCode();
    $q = $db->query("SELECT * FROM maps WHERE url='".$shorturl."'");
} while(mysqli_num_rows($q) > 0);
Sign up to request clarification or add additional context in comments.

3 Comments

How would I proceed when mysqli_num_rows === 0
@Donald After the loop, $shorturl will contain a unique random code. I assume you'd want to insert it into the database at that point.
I went searching around for the best way to do this and this one is the best. Very elegant and simple.
1
function regenerateCode(){

    global $connection;

    do{

        $serial2 = rand(0,7);

        $check_code = "SELECT * FROM `voters` WHERE `serial` = '$serial2'";

        $run_check_code = mysqli_query($connection,$check_code);

        $count = mysqli_num_rows($run_check_code);

    } while( $count > 0 );

    return $serial2;
}

1 Comment

While this code may answer the question, it would be better to include some context, explaining how it works and when to use it. Code-only answers are not useful in the long run.

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.