How can MySQL queries be properly executed in PHP to avoid errors like multiple queries in a single mysql_query() call?
To avoid errors like multiple queries in a single mysql_query() call, you should use the mysqli_multi_query() function in PHP to execute multiple queries in a single call. This function allows you to execute multiple queries separated by semicolons in a single string.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Multiple queries separated by semicolons
$sql = "SELECT * FROM table1; SELECT * FROM table2";
// Execute multiple queries
if ($mysqli->multi_query($sql)) {
do {
// Store and process the result set
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_assoc()) {
// Process each row
}
$result->free();
}
} while ($mysqli->next_result());
} else {
echo "Error executing multiple queries: " . $mysqli->error;
}
// Close connection
$mysqli->close();
Keywords
Related Questions
- What role does the use of HTTPS play in PHP applications, especially when accessing external links or resources?
- How can the implementation of separate methods or objects for each processing step improve the organization and readability of PHP setup scripts?
- How can error reporting be optimized to identify and resolve issues in PHP code?