Executing Multiple Queries in PHP using MySQL
Scenario:
You have multiple SQL queries that need to be executed together and the results combined. However, you're facing challenges in executing them seamlessly.
Solution 1: Using mysqli_multi_query
To execute multiple queries simultaneously, you can use the mysqli_multi_query() function. Here's how:
$link = mysqli_connect("server", "user", "password", "database"); $query = "QUERY1; QUERY2; QUERY3; QUERY4;"; if (mysqli_multi_query($link, $query)) { do { if ($result = mysqli_store_result($link)) { while ($row = mysqli_fetch_array($result)) { // Process results for current query echo $row['column1']; } mysqli_free_result($result); } } while (mysqli_next_result($link)); }
Solution 2: Separate Query Execution
If you prefer to execute the queries separately, you can do so as follows:
$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']; }
Remember to replace the server, user, password, and database values with the appropriate details for your database connection.
The above is the detailed content of How to Execute Multiple Queries in PHP using MySQL?. For more information, please follow other related articles on the PHP Chinese website!