How can multiple SQL statements be executed through a single query in PHP?
When executing multiple SQL statements in a single query in PHP, you can use the mysqli_multi_query function provided by the MySQLi extension. This function allows you to execute multiple SQL statements separated by semicolons in a single query string. It is important to handle any errors that may occur during the execution of the query.
<?php
$mysqli = new mysqli("localhost", "username", "password", "database");
$query = "
INSERT INTO table1 (column1, column2) VALUES ('value1', 'value2');
UPDATE table2 SET column1 = 'new_value' WHERE id = 1;
";
if ($mysqli->multi_query($query)) {
do {
if ($result = $mysqli->store_result()) {
$result->free();
}
} while ($mysqli->next_result());
} else {
echo "Error: " . $mysqli->error;
}
$mysqli->close();
?>
Keywords
Related Questions
- In what ways can the structure and format of the data in a .dat file impact the process of importing it into a MySQL database using PHP?
- What does the error message "Commands out of sync; you can't run this command now" indicate when executing MySQL queries in PHP?
- How can PHP be used to integrate existing search engines like Google into a website?