无法执行多行查询

Unable to get a multi line query executed

我有一个多行命令查询要执行。该查询包括创建临时 table 并使用它们返回 table。我试过的代码:

<?php

$mysqli = new mysqli("localhost", ...);

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}else{
    echo "good";
}

$query  = "CREATE TEMPORARY TABLE IF NOT EXISTS TT1 AS (Select * from `T1` order by `id` desc);";
$query .= "CREATE TEMPORARY TABLE IF NOT EXISTS TT2 AS (SELECT @n := @n + 1 `id`, `c1`, `c2`, `c3` FROM TT1, (SELECT @n := 0) m );";
$query .= "(Select `id`, `c3` from `TT2` limit 1) union (Select `id`, `c3` from `TT2` where `id`%25=0 ORDER BY `id` asc) union (Select `id`, `c3` from `TT2` where (`id`-1)%25=0 ORDER BY `id` asc) union (Select `id`, `c3` from `TT2` order by `id` desc limit 1) order by `c3` desc;";


/* execute multi query */
if ($mysqli->multi_query($query)) {
    do {
        /* store first result set */
        if ($result = $mysqli->store_result()) {
            while ($row = $result->fetch_row()) {
                printf("%s\n", $row[0]);
            }
            $result->free();
        }else{
            echo "bad2";
        }
        /* print divider */
        if ($mysqli->more_results()) {
            printf("-----------------\n");
        }else{
            echo "bad3";
        }
    } while ($mysqli->next_result());
}else{
    echo "bad1";
}

/* close connection */
$mysqli->close();

?>

我正在处理:

  1. 该程序不能很好地处理临时 tables,
  2. 程序在解析第一个查询后因错误退出,
  3. 我不知道如何实际获取上次查询的信息。

我应该提到查询在 phpMyAdmin 控制台中的工作完全符合预期。

编辑

至于调试,我添加了一些回声来寻找程序的流程。 程序输出:

goodbad1

将其拆分为 3 个单独的查询并一个接一个地执行。永远不要使用 multi_query()!

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", ...);
$mysqli->set_charset('utf8mb4'); // always set the charset

$query = "CREATE TEMPORARY TABLE IF NOT EXISTS TT1 AS (Select * from `T1` order by `id` desc);";
$mysqli->query($query);

$query = "CREATE TEMPORARY TABLE IF NOT EXISTS TT2 AS (SELECT @n := @n + 1 `id`, `c1`, `c2`, `c3` FROM TT1, (SELECT @n := 0) m );";
$mysqli->query($query);

$query = "(Select `id`, `c3` from `TT2` limit 1) union (Select `id`, `c3` from `TT2` where `id`%25=0 ORDER BY `id` asc) union (Select `id`, `c3` from `TT2` where (`id`-1)%25=0 ORDER BY `id` asc) union (Select `id`, `c3` from `TT2` order by `id` desc limit 1) order by `c3` desc;";
$stmt = $mysqli->prepare($query);
$stmt->execute();
$result = $stmt->get_result();

foreach ($result as $row) {
    // Do something
    echo $row['id'];
    echo $row['c3'];
}