Home > Backend Development > PHP Tutorial > How Can I Execute Multiple MySQL Queries Simultaneously?

How Can I Execute Multiple MySQL Queries Simultaneously?

Linda Hamilton
Release: 2024-12-24 00:10:20
Original
519 people have browsed it

How Can I Execute Multiple MySQL Queries Simultaneously?

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);
}
Copy after login

Additional Considerations:

  • mysqli_store_result() will return FALSE for queries without result sets, such as INSERT queries. Check mysqli_error() to confirm successful execution.
  • Note the use of ";" as the separator between queries.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template