我遇到了一个未知的问题,我创建了一个连接到 Mysql 的 PHP API(Slim 框架 + Slim PDO)。我使用 Nginx 作为 HTTP 服务器。 API 使用“device-id” header 来识别客户端(Android 应用程序)。令人担忧的是,最近 android 应用程序的更新使得在这个应用程序启动时,如果用户未知,它现在对结果 API 发出 2 个异步请求我发现自己在表用户中有两个条目携带相同的设备 ID
在中间件中
$user = new User($device_id, $ip);
在用户类
function __construct($device_id, $ip)
{
$this->_device_id = $device_id;
$this->_ip = $ip;
if ($this->isExists())
$this->updateInfo();
else
$this->createUser();
}
private function isExists()
{
global $db_core;
$selectStatement = $db_core->select(array('id', 'current_group'))
->from('users')
->where('device_id', '=', $this->_device_id);
$stmt = $selectStatement->execute();
if ($stmt->rowCount() > 0)
{
$u = $stmt->fetch();
$this->_id = $u['id'];
$this->_current_group = $u['current_group'];
return true;
}
return false;
}
createUser() 函数在用户表中创建一个条目,其中包含设备 ID 以及日期等其他信息。
预先感谢您的帮助
最佳答案
- 如果 device_id 字段在表中应该是唯一的,则为其添加一个唯一索引。
然后你就可以在 DUPLICATE KEY 上运行 mysql 查询,比如
INSERT INTO users (...) VALUES(:device_id, :ip, ...) ON DUPLICATE KEY UPDATE ip = values(ip) , ...
我不知道是否可以使用 Slim-PDO 运行这样的查询,但至少你可以使用通用的插入和更新查询,using exceptions, as shown in my article :
$this->_device_id = $device_id;
$this->_ip = $ip;
try {
$this->createUser();
} catch (PDOException $e) {
$search = "!Integrity constraint violation: 1062 Duplicate entry\ .*? for key 'device_id'!";
if (preg_match($search, $e->getMessage())) {
$this->updateInfo();
} else {
throw $e;
}
}
重要的是只更新特定错误,否则重新抛出。
关于php - 多个请求同时坏 SQL 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47853561/