在 PHP 中使用 MySQL 時,可能需要同時執行多個查詢。這對於在單一事務中建立視圖、臨時表和操作資料非常有用。
考慮以下程式碼片段:
$query1 = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X"; $query2 = "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH)"; $query3 = "CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank AS current_rank LEFT JOIN previous_rankings.rank AS prev_rank ON (current_rankings.player = previous_rankings.player)"; $query4 = "SELECT *, @rank_change = prev_rank - current_rank AS rank_change FROM final_output";
我們的目標是在單一PHP 腳本中執行所有四個查詢,然後使用mysql_fetch_array 檢索第四個查詢的結果。但是,當嘗試這樣做時,我們遇到錯誤或收到空的獲取數組。
要在單一 PHP 腳本中執行多個查詢,我們可以使用 mysqli_multi_query。這是更新後的程式碼:
$link = mysqli_connect("server", "user", "password", "database"); $query = " CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X; CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH); CREATE VIEW final_output AS SELECT current_rankings.player, current_rankings.rank AS current_rank LEFT JOIN previous_rankings.rank AS prev_rank ON (current_rankings.player = previous_rankings.player); SELECT *, @rank_change = prev_rank - current_rank AS rank_change FROM final_output; "; if (mysqli_multi_query($link, $query)) { do { if ($result = mysqli_store_result($link)) { while ($row = mysqli_fetch_array($result)) { echo $row['player'] . $row['current_rank'] . $row['prev_rank'] . $row['rank_change']; } mysqli_free_result($result); } } while (mysqli_next_result($link)); }
使用 mysqli_multi_query,我們將所有四個查詢連接到一個字串中並執行它們。然後,每個結果集都儲存在 $result 中,並且可以使用 mysqli_fetch_array 進行檢索。
也可以單獨執行查詢並將結果儲存在臨時表中。例如:
$query1 = "Create temporary table A select c1 from t1"; mysqli_query($link, $query1) or die(mysqli_error()); $query2 = "select c1 from A"; $result2 = mysqli_query($link, $query2) or die(mysqli_error()); while ($row = mysqli_fetch_array($result2)) { echo $row['c1']; }
在此方法中,第一個查詢建立一個名為 A 的臨時表。然後我們在第二個查詢中從 A 中選擇資料並檢索結果。
兩種方法都可以根據特定要求和資料庫結構來使用。
以上是如何在單一 PHP 腳本中執行多個 MySQL 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!