Php 组合选择和更新以避免重复选择

Php 组合选择和更新以避免重复选择,php,mysql,sql,mysqli,Php,Mysql,Sql,Mysqli,我想要组合选择和更新查询,以避免重复选择行 下面是我的示例代码: private function getNewRCode() { $getrcodesql = "SELECT * FROM `{$this->mysqlprefix}codes` WHERE `used` = 0 LIMIT 1;"; $getrcodequery = $this->mysqlconn->query($getrcodesql); if(@$getrcodequery-

我想要组合选择和更新查询,以避免重复选择行

下面是我的示例代码:

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
,以避免不同用户使用相同的代码

我希望你理解我的问题,并知道解决办法

您好,
弗雷德里克

如果你换一种方式做会更容易。
关键是,在执行
更新
选择之前,您的客户机可以生成一个唯一的值

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