Executing Multiple Queries with PDO
In PHP version 5.3, the PDO_MYSQL driver was replaced with PDO_MYSQLND, which introduced support for multiple queries. However, obtaining multiple result sets from these queries can be confusing.
Challenge:
Executing multiple SELECT queries using PDO_MYSQLND's query() method only returns the first result set. For example:
$db->query("SELECT 1; SELECT 2;")->fetchAll(PDO::FETCH_ASSOC);
This code will only return the result of the first query, which is:
array(1) { [0]=> array(1) { [1]=> string(1) "1" } }
Solution:
To retrieve subsequent result sets, you must use the PDOStatement::nextRowset() method.
$stmt = $db->query("SELECT 1; SELECT 2;"); $stmt->nextRowset(); var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));
This will return the result of the second query.
Implementation:
This implementation may seem a bit peculiar since it would be more convenient if multiple queries returned all results under one array. However, this design allows for fetching each result set using different fetch styles.
The above is the detailed content of How Can I Retrieve Multiple Result Sets from Multiple Queries Using PDO_MYSQLND?. For more information, please follow other related articles on the PHP Chinese website!