Appearance
Executing multiple SQL queries in one statement with PHP
In PHP, you can execute multiple SQL queries in one statement by using the mysqli_multi_query() function. This function allows you to pass in a string containing multiple SQL queries separated by a semicolon. Each query will be executed in the order they are written.
Here is an example of how to use mysqli_multi_query():
Example of executing multiple SQL queries in one statement by using the mysqli_multi_query() function in PHP
php
<?php
// $conn must be a valid mysqli connection object
$sql = "SELECT * FROM table1; SELECT * FROM table2;";
if (mysqli_multi_query($conn, $sql)) {
do {
/* store first result set */
if ($result = mysqli_store_result($conn)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
/* print divider */
if (mysqli_more_results($conn)) {
printf("----------------\n");
}
} while (mysqli_next_result($conn));
}It is important to note that not all SQL servers support multiple statements in one query, so you should check the documentation for the specific database you are using to see if this is a supported feature. The do...while loop ensures each result set is fully consumed before moving to the next query. Additionally, always validate and sanitize dynamic input before passing it to mysqli_multi_query() to prevent SQL injection vulnerabilities.