【问题标题】:PHP PDO / MySQLi doesn't return rows while query has mysql user-variablesPHP PDO / MySQLi在查询具有mysql用户变量时不返回行
【发布时间】:2018-05-08 14:01:02
【问题描述】:

我想执行并得到以下查询的结果:

$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-&gt;query($query); $sql-&gt;rowCount() 返回 0,没有结果行。我已经通过直接在数据库中执行查询来测试它并且它可以工作。

【问题讨论】:

  • 每个查询只执行一条语句。
  • 我同意@PaulSpiegel。没有理由将多条语句批处理到一次执行中,这会使代码更复杂,更难调试。
  • 还没有这么简单的答案。 :/ 谢谢!我试试看。

标签: php mysql mysqli pdo user-variables


【解决方案1】:

要走的路是进行多重查询,将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]);
   }
}

【讨论】:

    猜你喜欢
    • 2018-12-25
    • 1970-01-01
    • 2017-01-25
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多