multi_query
In this article, we will focus on the mysqli_multi_query() function in PHP, which is used to execute multiple queries in a single call. We will provide you with an overview of the function, how it works, and examples of its use.
Introduction to the mysqli_multi_query() function
The mysqli_multi_query() function is a built-in function in PHP that is used to execute multiple queries in a single call. This function is useful when you need to execute a series of queries that are dependent on each other or when you need to execute a batch of queries at once.
How to use the mysqli_multi_query() function
Using the mysqli_multi_query() function is very simple. You just need to call the function on a valid MySQLi connection with a string of multiple queries separated by semicolons. Here is an example:
How to use the mysqli_multi_query() function?
<?php
$mysqli = mysqli_connect("localhost", "username", "password", "database");
if (!$mysqli) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "INSERT INTO table1 VALUES ('value1', 'value2', 'value3');";
$query .= "UPDATE table2 SET column1 = 'newvalue' WHERE id = 1;";
if (mysqli_multi_query($mysqli, $query)) {
do {
if ($result = mysqli_store_result($mysqli)) {
while ($row = mysqli_fetch_row($result)) {
print_r($row);
}
mysqli_free_result($result);
}
} while (mysqli_next_result($mysqli));
} else {
echo "Error: " . mysqli_error($mysqli);
}
mysqli_close($mysqli);
?>In this example, we call the mysqli_connect() function to connect to a MySQL database with a username and password. We then create a string containing two queries separated by semicolons. We then call the mysqli_multi_query() function on the MySQLi connection to execute both queries at once. We then close the MySQLi connection using the mysqli_close() function.
Important considerations:
mysqli_multi_query()can return multiple result sets. Thedo...whileloop withmysqli_store_result()andmysqli_next_result()ensures all results are fetched and cleared properly to avoid "Commands out of sync" errors.- Always check the return value of
mysqli_multi_query()to handle execution failures gracefully. - This function does not support prepared statements directly. For queries involving user input, use
mysqli_prepare()for each query individually to prevent SQL injection. - For dependent queries that must succeed or fail together, prefer using transactions (
mysqli_begin_transaction(),mysqli_commit(),mysqli_rollback()) instead ofmysqli_multi_query()to ensure atomicity.
Conclusion
In conclusion, the mysqli_multi_query() function is a useful tool for executing multiple queries in a single call. By understanding how to use the function, handle multiple result sets, and apply best practices like transactions and prepared statements, you can create powerful and efficient MySQLi queries.
Practice
What is the primary purpose of the 'multi_query' function in PHP?