Why Can't I Run Multiple mysqli Queries Simultaneously?
As you've noticed, attempting to execute two separate MySQL queries using consecutive mysqli_query() calls will result in the second query failing. This behavior is due to security measures.
mysqli_multi_query() to the Rescue
Fortunately, mysqli provides the mysqli_multi_query() function specifically designed for executing multiple queries in a single database call.
Example Code
Here's an example of how to use mysqli_multi_query():
$mysqli = new mysqli($host, $user, $password, $database); // Create query string with multiple queries separated by ; $query = "INSERT INTO images (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName');"; $query .= "INSERT INTO images_history (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name, day, month, year) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName', '$day', '$month', '$year');"; // Execute query using mysqli_multi_query() $result = mysqli_multi_query($mysqli, $query); // Retrieve results if ($result) { do { $result = mysqli_store_result($mysqli); } while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); } else { echo "First query failed: " . mysqli_error($mysqli); }
Additional Considerations:
By using mysqli_multi_query(), you can efficiently execute multiple queries in a single database call, avoiding the second query failure issue.
The above is the detailed content of How Can I Execute Multiple MySQL Queries Simultaneously?. For more information, please follow other related articles on the PHP Chinese website!