samedi 2 mai 2015

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




Aucun commentaire:

Enregistrer un commentaire