0

ユーザーのキーコードを生成する必要があるので、dbで一意である必要があります。

キーが一意になるまで、このサイクルを繰り返す必要があります。

create key;

if($key is not in db){

  insert key;

}else{

repeat control with new key;

}

while()について考えましたが、その実装方法がわかりません。

dbの一意のキーを挿入してdbの一意のキーを更新する他の方法は、phpスクリプトを使用する代わりに、SQLクエリで直接記述できますか?(SQLクエリを使用した一意のキーの挿入/更新)

希望は明確な質問です。

4

3 に答える 3

4
$key = create_unique_key();

while( this_key_exists($key) )
{
 $key = create_unique_key();
}
//If you got here - the value of $key is unique and doesn't exist in db

説明: 最初にカスタム関数 を使用して一意のキーを作成したcreate_uniuqe_keyため、 の開始値が得られました$key。次に、whileループがあります。覚えておいてください。

while( 式 )

式が true を返す限り、ループに入ります。そのため、カスタム関数this_key_exists(true または false を返す) が true を返す (つまり、キーが一意でなく、データベースに存在する) 限り、新しい一意のキーを作成し、何度もチェックします。

于 2012-10-15T07:33:24.703 に答える
2

UUIDだけを使ってみてください

または、データベースの列に一意の制約を追加し、mysql エラーがなくなるまで行の挿入を試み続けます。

do {
    //insert using uniqid() or some random string
} while( $check_for_mysql_error );
于 2012-10-15T07:36:59.807 に答える
0
/**
 * Creates a unique URL for a page language by adding a 'dash number'
 * at the end of the provided user URL
 * @param string $page The current page
 * @param string $url The URL to make unique
 * @param type $lang The language to make unique for (you can have the same URL for same page in diffrent languages)
 * @return string The new URL
 */
function uniquePageUrl($page, $url, $lang){
    while(TRUE){
        $result = $this->db->from('pages')->where('page <>', $page)->where('lang',$lang)->where('url',$url)->limit(1)->get()->row();
        if($result) //we already have a page URL for this language like the one we try to use
            $url = increment_string($url,'-');
        else
            return $url;
    }
}
于 2012-10-15T07:34:32.850 に答える