开发者

Check a created string against database, and if found, create new string?

开发者 https://www.devze.com 2023-03-24 04:34 出处:网络
Pretty simple, however, I\'ve yet to find a real straight and appropriate solution; I\'ve currently got my own function that creates a random string, by running two mt_rand() functions from 1 to maxi

Pretty simple, however, I've yet to find a real straight and appropriate solution;

I've currently got my own function that creates a random string, by running two mt_rand() functions from 1 to maximum integers, then wrapping the results in two dechex() 开发者_C百科functions, and concatenating them into a single string.

I haven't done the stats on it, but, the chances of two of these strings being the same is pretty low.

However, I'll obviously need a backup solution which is why I want to perform a query against a database, and see if it exists as an entry, and if it does, re-invoke my own function to create a random string, query again, and loop until a non-existent string is found.

I've had a look at a ton of forum threads, and a few SO questions, but have yet to found a concise answer.

Any help would be greatly appreciated, thanks!


$int_affected = 0;
while(!$int_affected) {
    /* Set $integer */
    mysql_query("INSERT IGNORE INTO table (value) VALUES ({$integer})");

    $int_affected = mysql_affected_rows();
}

Is this something you're looking for?


You need a recursive function. Something like:

function makeString() {

    // Create our random string
    $string = "";
    $characters = array('a', 'b', 'c', 'd');

    for ($i = 0; $i < 4; $i++) {

        $string .= $characters[mt_rand(0, 4)];
    }

    $query = "SELECT COUNT(*)
    FROM myTable
    WHERE string = '{$string}'";

    $result = mysql_query($query);
    $row = mysql_fetch_assoc($result);

    if ($row['COUNT(*)'] > 0) { // if it already exists, do it again

        $string = makeString();
    }

    return $string;
}


This isn't the most elegant solution, but it will work:

$result = queryForUnique();

$unique_string = your_described_function();
$how_many_times = 0;
while(in_array($unique_string, $result) !== false){
    if($how_many_times > 10){
        throw new Exception("Failed to find a unique string! Aborting!");
    }

    $unique_string = your_described_function();
    $how_many_times++;
}

Where queryForUnique($string) is a wrapper for a SELECT statement

Edit:
Took the query out of the loop, it is bad practice to have a SELECT query in a loop.


Might want to review your control structures:
http://php.net/manual/en/language.control-structures.php

0

精彩评论

暂无评论...
验证码 换一张
取 消