gpt4 book ai didi

php - 组合 SELECT 和 UPDATE 以避免重复选择

转载 作者:可可西里 更新时间:2023-11-01 08:36:26 26 4
gpt4 key购买 nike

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

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

您好,弗雷德里克

最佳答案

反过来做会更容易。
关键是您的客户端可以在您执行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

关于php - 组合 SELECT 和 UPDATE 以避免重复选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10461514/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com