What are the advantages and disadvantages of using multi_query in PHP for executing multiple SELECT queries compared to other methods?
When executing multiple SELECT queries in PHP, using multi_query can be advantageous as it allows you to send multiple queries in a single call to the database server, which can improve performance by reducing the number of round trips. However, multi_query can be less secure compared to prepared statements or stored procedures, as it does not automatically escape input values, leaving your application vulnerable to SQL injection attacks.
<?php
// Establish a connection to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Define multiple SELECT queries
$query1 = "SELECT * FROM table1";
$query2 = "SELECT * FROM table2";
// Execute the multiple queries using multi_query
if ($mysqli->multi_query($query1 . ";" . $query2)) {
do {
// Store and process the results of the first query
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
// Process each row from the first query
}
$result->free();
}
// Move to the next result
} while ($mysqli->next_result());
} else {
// Handle query execution error
echo "Error executing multiple queries: " . $mysqli->error;
}
// Close the database connection
$mysqli->close();
?>