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 best practices should be followed when preparing and executing SQL statements in PHP using PDO for database operations?
- How can PHP be used to automatically notify the client when the server receives an image for processing and display on a website?
- How can the PHP code be modified to rename the uploaded images sequentially, such as 0000001.jpg, 0000002.jpg, etc.?