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();
?>