Home > Database > Mysql Tutorial > How to Retrieve Multiple Result Sets from a Single PDO Query?

How to Retrieve Multiple Result Sets from a Single PDO Query?

Patricia Arquette
Release: 2024-11-17 12:06:02
Original
935 people have browsed it

How to Retrieve Multiple Result Sets from a Single PDO Query?

PDO Multiple Queries: Retrieving Multiple Result Sets

PHP 5.3 introduced support for multiple queries in the PDO_MYSQLND driver, allowing you to execute multiple SELECT queries in a single call. However, retrieving the result sets from these queries can be confusing.

Consider the following query:

$db->query("SELECT 1; SELECT 2;")
Copy after login

This query executes two SELECT queries. The fetchAll(PDO::FETCH_ASSOC) method is then used to retrieve the result set. However, this only returns the results of the first query:

array(1) {
  [0] =>
  array(1) {
    [1] =>
    string(1) "1"
  }
}
Copy after login

Using PDOStatement::nextRowset

To retrieve the results of the second query, you need to use the PDOStatement::nextRowset method. This method allows you to move the statement cursor to the next result set:

$stmt = $db->query("SELECT 1; SELECT 2;");
$stmt->nextRowset();
var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));
Copy after login

This will return the results of the second query:

array(1) {
  [0] =>
  array(1) {
    [2] =>
    string(1) "2"
  }
}
Copy after login

Multiple FETCH Styles

The advantage of using PDOStatement::nextRowset is that it allows you to fetch each query using different FETCH styles. For example:

$stmt = $db->query("SELECT 1; SELECT 'a';");
$stmt->nextRowset();
$first = $stmt->fetchColumn(); // fetch first column of second query
$stmt->nextRowset();
$second = $stmt->fetch(PDO::FETCH_ASSOC); // fetch associative array of third query
Copy after login

This gives you greater flexibility when working with multiple queries.

The above is the detailed content of How to Retrieve Multiple Result Sets from a Single PDO Query?. 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