查詢

mysqli::multi_query()函式—用法及示例

「 執行多個SQL查詢 」


mysqli::multi_query()函式用於執行多個SQL查詢。

用法:

mysqli::multi_query(string $query)

引數:

  • $query:包含多個SQL查詢語句的字串。

返回值:

  • 如果查詢成功,則返回true。
  • 如果查詢失敗,則返回false。

注意事項:

  • 該函式執行多個SQL查詢,每個查詢之間使用分號(;)分隔。
  • 該函式只能用於執行多個查詢,不能用於執行儲存過程或函式。

示例:

$mysqli = new mysqli("localhost", "username", "password", "database");

// 檢查連線是否成功
if ($mysqli->connect_errno) {
    echo "連線資料庫失敗: " . $mysqli->connect_error;
    exit();
}

// 執行多個查詢
$query = "SELECT * FROM table1; SELECT * FROM table2; SELECT * FROM table3";
if ($mysqli->multi_query($query)) {
    do {
        // 獲取結果集
        if ($result = $mysqli->store_result()) {
            // 處理結果集
            while ($row = $result->fetch_assoc()) {
                // 輸出資料
                echo $row['column1'] . " " . $row['column2'] . "<br>";
            }
            // 釋放結果集
            $result->free();
        }
        // 檢查是否還有更多的結果集
        if ($mysqli->more_results()) {
            // 轉到下一個結果集
            $mysqli->next_result();
        }
    } while ($mysqli->more_results());
} else {
    echo "查詢失敗: " . $mysqli->error;
}

// 關閉資料庫連線
$mysqli->close();

上述示例中,我們首先建立了一個mysqli物件,並連線到資料庫。然後,我們使用multi_query()函式執行了三個查詢語句。在迴圈中,我們使用store_result()方法獲取每個查詢的結果集,並使用fetch_assoc()方法遍歷結果集中的行。最後,我們檢查是否還有更多的結果集,並使用next_result()方法轉到下一個結果集。迴圈結束後,我們關閉了資料庫連線。

補充糾錯
上一個函式: mysqli::next_result()函式
下一個函式: mysqli::more_results()函式
熱門PHP函式
分享連結