Zend TableGateway无法执行2次连续查询

时间:2018-04-17 14:39:37

标签: zend-framework slim

我从slim-api-skeleton开始使用Zend TableGateway开始学习Slim已经好几周了。

似乎我无法使用TableGateway运行2次连续查询。它总是产生(不仅仅是更新):

"Statement couldn't be produced with sql: UPDATE `users` SET `last_access` = NOW() WHERE `id` = ?"

这是ZendUserRepository类中的代码:

public function __construct(array $config) {
    $adapter = new Adapter($config);
    $this->table = new TableGateway("users", $adapter);
}

...

public function footprint(int $id): void {
    $data = ['last_access' => new Predicate\Expression('NOW()')];
    $where = ['id' => $id];
    $this->table->update($data, $where);
}

public function authenticate(string $username, string $password): bool {
    $where = [
        'username' => $username,
        new Predicate\IsNotNull('roles')
    ];
    $rowset = $this->table->select($where);
    if (null === $row = $rowset->current()) {
        return false;
    }
    $data = (array) $row;
    if(password_verify($password, $data['password'])) {
        $this->footprint($data['id']);
        return true;
    }
    return false;
}

这让我感到沮丧。由于更新功能也使用2个连续查询。

public function update(User $user): void {
    $data = $this->hydrator->extract($user);
    if (!$this->contains($user)) {
        throw new UserNotFoundException;
    }
    $where = ["id" => $user->getId()];
    $this->table->update($data, $where);
}

public function contains(User $user): bool {
    try {
        $this->get($user->getId());
    } catch (UserNotFoundException $exception) {
        return false;
    }
    return true;
}

谢谢。

1 个答案:

答案 0 :(得分:0)

使用PHPUnit测试,我得到以下结果:

Zend\Db\Adapter\Exception\InvalidQueryException: Statement couldn't be produced with sql: UPDATE `users` SET `last_access` = NOW() WHERE `id` = ?

/vagrant/vendor/zendframework/zend-db/src/Adapter/Driver/Mysqli/Statement.php:208
/vagrant/vendor/zendframework/zend-db/src/Adapter/Driver/Mysqli/Statement.php:229
/vagrant/vendor/zendframework/zend-db/src/TableGateway/AbstractTableGateway.php:391
/vagrant/vendor/zendframework/zend-db/src/TableGateway/AbstractTableGateway.php:349
/vagrant/src/Infrastructure/ZendUserRepository.php:90
/vagrant/src/Infrastructure/ZendUserRepository.php:104
/vagrant/src/Application/User/UserAuthenticationHandler.php:19
/vagrant/tests/Application/User/UserAuthenticationHandlerTest.php:41

Caused by
Zend\Db\Adapter\Exception\ErrorException: Commands out of sync; you can't run this command now

从Google导致https://stackoverflow.com/a/614741/3164944

  

你不能同时拥有两个查询,因为mysqli使用了无缓冲的查询   默认(对于预备语句;对于vanilla来说则相反)   的mysql_query)。您可以将第一个获取到数组中   循环,或告诉mysqli缓冲查询(使用$ stmt-> store_result())。

解决了其他配置:

[
    "driver" => "Mysqli",
    "database" => getenv("DB_NAME"),
    "username" => getenv("DB_USER"),
    "password" => getenv("DB_PASSWORD"),
    "hostname" => getenv("DB_HOST"),
    "charset" => "utf8",
    'options' => ['buffer_results' => true],
]

来自https://stackoverflow.com/a/43863554/3164944

相关问题