ngplayground
ngplayground

Reputation: 21617

PHP if random code exists in database regenerate random code

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;
}

Upvotes: 1

Views: 938

Answers (2)

SABS-TECH
SABS-TECH

Reputation: 13

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;
}

Upvotes: 1

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

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);

Upvotes: 6

Related Questions