Managing Multiple Queries in PDO
PDO introduced support for executing multiple queries simultaneously through its PDO_MYSQLND driver. However, retrieving multiple result sets from these queries presents a challenge.
Consider the following code sample:
$db->query("SELECT 1; SELECT 2;")->fetchAll(PDO::FETCH_ASSOC);
Executing this code will return only the result set for the first SELECT query. To access the results of the second SELECT query, you must use the PDOStatement::nextRowset method.
$stmt = $db->query("SELECT 1; SELECT 2;"); $stmt->nextRowset(); var_dump($stmt->fetchAll(PDO::FETCH_ASSOC));
With PDOStatement::nextRowset, you can iterate through multiple result sets, allowing you to handle them separately.
This implementation may seem unusual, but it offers flexibility by allowing different FETCH styles to be applied to individual queries. However, it would be simpler if all result sets were returned under one array.
The above is the detailed content of How to Retrieve Multiple Result Sets from Simultaneous PDO Queries?. For more information, please follow other related articles on the PHP Chinese website!