Home > Article > Backend Development > How to Execute Multiple SQL Queries in a Single Result Set with PHP/MySQL?
Executing Multiple Queries in PHP/MySQL
Question:
How can I combine multiple SQL queries into a single result set in PHP using MySQL?
Answer:
To execute multiple concatenated queries in PHP using MySQL, follow these steps:
$query = "SQL STATEMENT 1;;SQL STATEMENT 2;;SQL STATEMENT 3";
if (mysqli_multi_query($link, $query)) { do { // Store and process results } while (mysqli_next_result($link)); }
Example:
$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)) { // Process results } mysqli_free_result($result); } } while (mysqli_next_result($link)); }
Alternative Approach:
Alternatively, you can execute each query separately and process the results one by one. This approach is recommended if the queries are not interdependent.
$query1 = "Create temporary table A select c1 from t1"; $result1 = mysqli_query($link, $query1); $query2 = "select c1 from A"; $result2 = mysqli_query($link, $query2); while($row = mysqli_fetch_array($result2)) { // Process results }
The above is the detailed content of How to Execute Multiple SQL Queries in a Single Result Set with PHP/MySQL?. For more information, please follow other related articles on the PHP Chinese website!