Multiple queries simultaneously with poor SQL results

I ran into an unknown problem, I created a PHP API (Slim framework + Slim PDO) connected to Mysql. I am using Nginx as an HTTP server. The API uses the "device-id" header to recognize the client (Android application). The problem is that recently updating the Android application does that when it starts it now makes 2 asynchronous requests in the results API if the user is unknown. I am with two records in a table, users having the same device identifier

In middleware

$user = new User($device_id, $ip);

In user 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;
  }

The createUser () function creates an entry in the user table with the device identifier, as well as other information, such as date, etc.

User Lists

+4
1
  • device_id , .
  • mysql- ON DUPLICATE KEY,

    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;
    }
}

.

+1

Source: https://habr.com/ru/post/1690918/


All Articles