Check a created string against database, and if found, create new string?
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
精彩评论