简体   繁体   English

当查询具有mysql用户变量时,PHP PDO / MySQLi不返回行

[英]PHP PDO / MySQLi doesn't return rows while query has mysql user-variables

I want to execute and get the results of the following query: 我要执行并获取以下查询的结果:

$query = <<<SQL
    set @num := 0, @priority := '';
    select * from (
        select
        id, status_ts,
        @num := if(@priority = priority, @num + 1, 1) as _row_number,
        @priority := priority as priority
        FROM ($priority_query) as get_priority
        ORDER BY priority DESC, status_ts ASC
    ) as items where items._row_number <= CEIL(priority);
SQL;

The $sql = $PDO->query($query); $sql->rowCount() $sql = $PDO->query($query); $sql->rowCount() $sql = $PDO->query($query); $sql->rowCount() returns 0, there are no result rows. $sql = $PDO->query($query); $sql->rowCount()返回0,没有结果行。 I've tested the query by executing it directly in the DB and it works. 我已经通过直接在数据库中执行查询来测试查询,并且它可以正常工作。

The way to go was to make a multiple query, changing set to select and then properly iterating through the results. 进行的方法是进行多个查询,将set更改为select ,然后适当地迭代结果。

$query = <<<SQL
    select @num := 0, @priority := '';
    select * from (
        select
        id, status_ts,
        @num := if(@priority = priority, @num + 1, 1) as _row_number,
        @priority := priority as priority
        FROM ($priority_query) as get_priority
        ORDER BY priority DESC, status_ts ASC
    ) as items where items._row_number <= CEIL(priority);
SQL;

PDO PDO

    $sql = $pdo->query($query);

    if ($sql && $sql->nextRowset()) {
        $items = [];
        $numRows = $sql->rowCount();
        if (($numRows > 0)) {
            $items = $sql->fetchAll(\PDO::FETCH_OBJ);
        }
    } else {
        $error = $this->DB->pdo->errorInfo();
        throw new \Exception($error[2]);
    }

MySQLi MySQLi的

$mysqli->multi_query($query);
$mysqli->next_result();

if ($result = $mysqli->store_result()) {
   while ($row = $result->fetch_row()) {
      printf("%s\n", $row[0]);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM