使用 MySQL 在 PHP 中執行多個查詢
考慮一個場景,您需要在單一 PHP 腳本中執行多個 SQL 查詢。一種常見的方法是使用 mysqli_multi_query() 函數,它允許您將多個查詢連接到一個字串中。
以下是如何實現此目的的範例:
// Create database connection $conn = mysqli_connect('server', 'user', 'password', 'database'); // Construct the multiple queries as a single string $query = "CREATE VIEW current_rankings AS SELECT * FROM main_table WHERE date = X;"; $query .= "CREATE VIEW previous_rankings AS SELECT rank FROM main_table WHERE date = date_sub('X', INTERVAL 1 MONTH);"; $query .= "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);"; $query .= "SELECT *, @rank_change = prev_rank - current_rank as rank_change from final_output;"; // Execute the multiple queries if (mysqli_multi_query($conn, $query)) { // Process each result set do { // Check for the first result set if ($result = mysqli_store_result($conn)) { // Fetch and display the results while ($row = mysqli_fetch_array($result)) { echo $row['player'] . ' ' . $row['current_rank'] . ' ' . $row['prev_rank'] . ' ' . $row['rank_change']; } // Free the result set mysqli_free_result($result); } } while (mysqli_next_result($conn)); } else { // Handle any errors echo mysqli_error($conn); }
或者,如果您希望單獨執行每個查詢,可以使用mysqli_query() 函數多個times:
// Create temporary table A $query1 = "Create temporary table A select c1 from t1"; mysqli_query($conn, $query1) or die(mysqli_error($conn)); // Select from temporary table A $query2 = "select c1 from A"; $result2 = mysqli_query($conn, $query2) or die(mysqli_error($conn)); // Fetch and display the results while ($row = mysqli_fetch_array($result2)) { echo $row['c1']; }
選擇透過mysqli_multi_query() 將多個查詢連接成單一字串還是透過mysqli_query() 單獨執行它們取決於您的特定要求和效能考慮。
以上是如何在 PHP 中有效率地執行多個 MySQL 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!