【问题标题】:Several requests at the same time bad SQL results多个请求同时出现坏 SQL 结果
【发布时间】:2017-12-17 18:49:59
【问题描述】:

我遇到一个未知问题,我创建了一个连接到 Mysql 的 PHP API(Slim 框架 + Slim PDO)。我使用 Nginx 作为 HTTP 服务器。 API 使用“device-id”标头来识别客户端(Android 应用程序)。令人担忧的是,最近 android 应用程序的更新使得在启动这个应用程序时,如果用户未知,它现在会在结果 API 上发出 2 个异步请求我发现自己在表 users 中有两个条目携带相同的设备 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

提前感谢您的帮助

【问题讨论】:

    标签: php mysql nginx pdo slim


    【解决方案1】:
    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;
        }
    }
    

    只更新特定错误非常重要,否则重新抛出它。

    【讨论】:

    • 请注意:必须设置 PDO 连接选项 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,,以便抛出 PDOException
    猜你喜欢
    • 2019-08-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-28
    • 2022-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多