几个请求同时坏 SQL 结果
Several requests at the same time bad SQL results
我遇到了一个未知问题,我创建了一个 PHP API(Slim 框架 + Slim PDO)连接到 Mysql。我使用 Nginx 作为 HTTP 服务器。 API 使用 "device-id" header 来识别客户端(一个 android 应用程序)。令人担忧的是,最近 android 应用程序的更新使得在启动此应用程序时它现在对结果发出 2 个异步请求 API 如果用户未知,我发现自己在table 用户携带相同device-id
在中间件中
$user = new User($device_id, $ip);
在用户class
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() 函数在用户 table 中创建一个条目 device-id 以及日期等其他信息。
User lists
提前感谢您的帮助
- 如果 device_id 字段在 table 中应该是唯一的,则为其添加一个 唯一索引。
然后你就可以运行一个mysql查询DUPLICATE KEY,比如[=13=]
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 API(Slim 框架 + Slim PDO)连接到 Mysql。我使用 Nginx 作为 HTTP 服务器。 API 使用 "device-id" header 来识别客户端(一个 android 应用程序)。令人担忧的是,最近 android 应用程序的更新使得在启动此应用程序时它现在对结果发出 2 个异步请求 API 如果用户未知,我发现自己在table 用户携带相同device-id
在中间件中
$user = new User($device_id, $ip);
在用户class
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() 函数在用户 table 中创建一个条目 device-id 以及日期等其他信息。
User lists
提前感谢您的帮助
- 如果 device_id 字段在 table 中应该是唯一的,则为其添加一个 唯一索引。
然后你就可以运行一个mysql查询DUPLICATE KEY,比如[=13=]
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;
}
}
重要的是只更新特定错误,否则重新抛出。