php - 多个请求同时坏 SQL 结果

标签 php mysql nginx pdo slim

我遇到了一个未知的问题,我创建了一个连接到 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 以及日期等其他信息。

User lists

预先感谢您的帮助

最佳答案

  1. 如果 device_id 字段在表中应该是唯一的,则为其添加一个唯一索引
  2. 然后你就可以在 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/

相关文章:

nginx - 回退到 nginx 中的默认/共享文件

nginx - Xdebug 设置 cookie XDEBUG_SESSION 次数太多

php - 从数据库中检索数据时换行

php - Sweet Alert 2 - "confirmButtonText"按钮中的链接

php - 为什么要使用 javascript 验证表单?

php - 您应该将用户登录详细信息存储在与您的网站相同的数据库中吗?

php PDO使用占位符插入批处理多行

c# - 使用 SQL Server、MySQL 数据库创建唯一约束

mysql - 如何在 MySQL 中获取行出现值?

Nginx 如何将位置列入白名单以进行速率限制