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

时间:2018-05-08 14:01:03

标签: php mysql mysqli pdo user-variables

我想执行并获取以下查询的结果:

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

$sql = $PDO->query($query); $sql->rowCount()返回0,没有结果行。我通过直接在数据库中执行查询来测试查询,它可以工作。

1 个答案:

答案 0 :(得分:0)

可行的方法是进行多次查询,将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

    $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->multi_query($query);
$mysqli->next_result();

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