Are there any best practices for ensuring transaction safety when using multi_query in PHP?
When using multi_query in PHP to execute multiple SQL queries in a single call, it is important to ensure transaction safety to prevent data inconsistencies or corruption. One best practice is to use transactions to group the queries together and rollback the entire transaction if any query fails. This helps maintain data integrity and ensures that all queries are either successfully executed or none at all.
<?php
// Establish a database connection
$mysqli = new mysqli("localhost", "username", "password", "database");
// Begin a transaction
$mysqli->begin_transaction();
// Execute multiple queries using multi_query
$query = "INSERT INTO table1 (column1) VALUES ('value1');";
$query .= "UPDATE table2 SET column2 = 'value2';";
if ($mysqli->multi_query($query)) {
// Commit the transaction if all queries are successful
$mysqli->commit();
echo "Transaction successful.";
} else {
// Rollback the transaction if any query fails
$mysqli->rollback();
echo "Transaction failed.";
}
// Close the database connection
$mysqli->close();
?>