2012-05-05 17 views
3

SELECTとUPDATEクエリを組み合わせて、行の重複を避けるためです。私は同じコードが異なるユーザのために使用されることを避けるために、一度$getrcodesql$updatercodesqlを実行したいと思いますSELECTとUPDATEを組み合わせて重複する選択を避ける

private function getNewRCode() { 

    $getrcodesql = "SELECT * FROM `{$this->mysqlprefix}codes` WHERE `used` = 0 LIMIT 1;"; 
    $getrcodequery = $this->mysqlconn->query($getrcodesql); 

    if(@$getrcodequery->num_rows > 0){ 

     $rcode = $getrcodequery->fetch_array(); 

     $updatercodesql = "UPDATE `{$this->mysqlprefix}codes` SET `used` = '1' WHERE `id` = {$rcode['id']};"; 
     $this->mysqlconn->query($updatercodesql); 

     $updateusersql = "UPDATE `{$this->mysqlprefix}users` SET `used_codes` = `used_codes`+1, `last_code` = '{$rcode['code']}', `last_code_date` = NOW() WHERE `uid` = {$this->uid};"; 
     $this->mysqlconn->query($updateusersql); 

     $output = array('code' => $rcode['code'], 
         'time' => time() + 60*60*$this->houroffset, 
         'now' => time() 
         ); 

     return $output; 

    } 

} 

はここに私のコード例です。

私の問題を理解し、これに対する解決策をご理解いただければ幸いです。

挨拶、 フレデリック

答えて

2

あなたはそれ以外の方法ラウンドを行う場合、それは簡単です。
クライアントがの前にUPDATESELECTの前に固有の値を生成できるということです。

変更何か他のものにあなたのused列の種類、あなたはそれにGUIDまたはタイムスタンプを保存することができるように、とだけではなく、0と1
(私は、PHP/MySQLの専門家ではありませんあなたはおそらく、あなたが()擬似コードでこれを行うことができます)

を正確に何を使用するには私よりもよく知っている:

// create unique GUID (I don't know how to do this in PHP, but you probably do) 
$guid = Create_Guid_In_PHP(); 

// update one row and set the GUID that you just created 
update codes 
set used = '$guid' 
where id in 
(
    select id 
    from codes 
    where used = '' 
    limit 1 
); 

// now you can be sure that no one else selected the row with "your" GUID 
select * 
from codes 
where used = '$guid' 

// do your stuff with the selected row 
+0

私はそれをこのように実装します、この素晴らしいアイデアをありがとうございました。 –

関連する問題