0
$new_random_string = substr(str_shuffle('0123456789'), 0, 2);

$strings = mysql_query("SELECT `string` FROM `table`");
while ($string = mysql_fetch_row($strings)) {

if ($new_random_string == $string[0]) 

// generate new random string

}

mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");

データベースにすでに存在する場合に備えて、ループで新しい文字列を生成したいと思います。ありがとう。

4

4 に答える 4

1

ランダムな文字列を生成してデータベースに挿入しようとしているようですが、重複することはできないという制限があります。

重複がないようにするための最善の方法は、その列にUNIQUEインデックスを作成することです。次に、データベースは重複する値が存在しないことを確認します。

新しい値を挿入するには、データベースにクエリを実行して、挿入する前に特定の文字列がすでに存在するかどうかを確認します。または、先に進んで挿入を試み、それが機能するかどうかを確認することもできます。UNIQUE制約により、重複が挿入されるのを防ぎます。

于 2012-07-26T09:04:51.207 に答える
0
while(1)
{
   // generate new random string
   if(mysql_result(mysql_query("SELECT COUNT(*) FROM `table` WHERE `string` ".$new_random_string), 0) == 0){
       mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");
       break;
   }
}
于 2012-07-26T09:05:50.170 に答える
0
function gen_string() {
   return substr(str_shuffle('0123456789'), 0, 2);
}

do {
$rand = gen_string();
$query = mysql_query("SELECT count(*) as rows FROM `table` where `string` ='".$rand ."'; ");

$row = mysql_fetch_row($query);

} while ($row['rows']>0);

mysql_query("INSERT INTO `table` (`string`) VALUES ('".$rand."')");

テストされていませんが、動作するはずです。

于 2012-07-26T09:06:13.353 に答える
0
do{

    $new_random_string = substr(str_shuffle('0123456789'), 0, 2);
    $string = mysql_query("SELECT `string` FROM `table` WHERE `string` = $new_random_string");
    $string = mysql_fetch_row($strings)

}while($new_random_string == $string[0]);

mysql_query("INSERT INTO `table` (`string`) VALUES ('".$new_random_string."')");
于 2012-07-26T09:08:00.653 に答える