Home > Database > Mysql Tutorial > How Can I Efficiently Execute and Retrieve Results from Multiple MySQL Queries in a Single PHP Script?

How Can I Efficiently Execute and Retrieve Results from Multiple MySQL Queries in a Single PHP Script?

Patricia Arquette
Release: 2024-12-09 15:32:12
Original
344 people have browsed it

How Can I Efficiently Execute and Retrieve Results from Multiple MySQL Queries in a Single PHP Script?

Multiple Query Execution in PHP with MySQL

This question explores the challenge of executing multiple MySQL queries in a single PHP script and retrieving the combined results.

A user provided a script that included multiple queries separated by semicolons, but was unable to retrieve the results using mysql_fetch_array().

The solution from php.net suggests utilizing mysqli_multi_query(), which allows you to execute concatenated queries within a single function call. Here's an example:

if (mysqli_multi_query($link, $query)) {
  do {
    if ($result = mysqli_store_result($link)) {
      while ($row = mysqli_fetch_array($result)) {
        // Process and print the results
      }
      mysqli_free_result($result);
    }
  } while (mysqli_next_result($link));
}
Copy after login

In this script, the mysqli_multi_query() function is used to execute the concatenated SQL statements. The mysqli_store_result() function is then used to retrieve the result set from the executed query. The mysqli_fetch_array() function is used to iterate through the result set and retrieve the data row by row.

As an alternative to executing multiple queries in a single call, the user also suggested executing them separately and retrieving the results individually using mysqli_query() and mysqli_fetch_array().

$query1 = "Create temporary table A select c1 from t1";
$result1 = mysqli_query($link, $query1) or die(mysqli_error());

$query2 = "select c1 from A";
$result2 = mysqli_query($link, $query2) or die(mysqli_error());

while($row = mysqli_fetch_array($result2)) {
  // Process and print the results
}
Copy after login

By leveraging one of these methods, developers can execute multiple MySQL queries within a PHP script and retrieve the combined results for further processing.

The above is the detailed content of How Can I Efficiently Execute and Retrieve Results from Multiple MySQL Queries in a Single PHP Script?. 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