我面临一个未知问题,我创建了连接到mySQL的PHP API(Slim Framework Slim PDO)。我将NGINX用作HTTP服务器。API使用"设备ID"标头识别客户端(Android应用程序)。令人担忧的是,最近对Android应用程序的更新使得在此启动时,如果用户尚不清楚,则现在可以在结果API上进行2个异步请求
中间件
$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字段,则为其添加唯一索引。
-
然后您将能够在重复键上运行MySQL查询,例如
INSERT INTO users (...) VALUES(:device_id, :ip, ...) ON DUPLICATE KEY UPDATE ip = values(ip) , ...
我不知道是否可以使用Slim-PDO运行这样的查询,但是至少您可以使用异常进行通用插入和更新查询,如我的文章:
所示$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;
}
}
仅更新某些错误,否则将其重新置换非常重要。