The mysqli_multi_query()
function in PHP allows you to execute multiple SQL statements in a single function call using the MySQLi extension. This is especially useful when performing a series of related queries, like inserting multiple rows or executing a combination of SELECT, INSERT, UPDATE, or DELETE statements.
🔹 Syntax:
bool mysqli_multi_query(mysqli $link, string $query)
$link
: The MySQLi connection object.$query
: A string containing one or more SQL statements separated by semicolons (;
).- Returns
true
on success, orfalse
on failure.
✅ Example 1: Multiple INSERT Statements
<?php
$mysqli = new mysqli("localhost", "root", "", "testdb");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com');";
$sql .= "INSERT INTO users (name, email) VALUES ('Bob', 'bob@example.com');";
$sql .= "INSERT INTO users (name, email) VALUES ('Charlie', 'charlie@example.com');";
if ($mysqli->multi_query($sql)) {
echo "Multiple records inserted successfully.";
} else {
echo "Error: " . $mysqli->error;
}
$mysqli->close();
?>
✅ Example 2: SELECT Followed by Another Query
<?php
$mysqli = new mysqli("localhost", "root", "", "testdb");
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "SELECT * FROM users;";
$sql .= "SELECT * FROM orders;";
if ($mysqli->multi_query($sql)) {
do {
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
print_r($row);
}
$result->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
} else {
echo "Error: " . $mysqli->error;
}
$mysqli->close();
?>
⚠️ Notes:
- Always check for SQL injection when using dynamic queries.
- Use
mysqli->store_result()
to retrieve results. - Use
mysqli->next_result()
to move to the next result set. - Avoid in user-facing apps unless you're validating and sanitizing all inputs properly.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.