结合SELECT和UPDATE以避免重复选择

时间:2012-05-05 11:42:56

标签: php mysql sql mysqli

我想组合一个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;

    }

}

我想立即执行$getrcodesql$updatercodesql,以避免相同的代码用于不同的用户。

我希望你能理解我的问题并知道解决方案。

问候, 弗雷德里克

1 个答案:

答案 0 :(得分: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