How to Retrieve Multiple Result Sets from Stored Procedures in MySQL with PHP/mysqli and PDO?

DDD
Release: 2024-10-30 19:30:02
Original
792 people have browsed it

How to Retrieve Multiple Result Sets from Stored Procedures in MySQL with PHP/mysqli and PDO?

Handling Multiple Result Sets from Stored Procedures in MySQL Using PHP/mysqli

Retrieving multiple result sets from stored procedures in PHP/mysqli can be achieved by employing the mysqli_stmt_next_result() function. The following example demonstrates how to use this function to advance to the second result set:

<code class="php">$stmt = mysqli_prepare($db, 'CALL multiples(?, ?)');
mysqli_stmt_bind_param($stmt, 'ii', $param1, $param2);
mysqli_stmt_execute($stmt);

// Fetch and process the first result set
$result1 = mysqli_stmt_get_result($stmt);
while ($row1 = mysqli_fetch_assoc($result1)) {
    // Process row1
}

// Advance to the second result set
mysqli_stmt_next_result($stmt);
if (mysqli_stmt_error($stmt)) {
    die('Failed to advance to the second result set: ' . mysqli_stmt_error($stmt));
}

// Fetch and process the second result set
$result2 = mysqli_stmt_get_result($stmt);
while ($row2 = mysqli_fetch_assoc($result2)) {
    // Process row2
}</code>
Copy after login

PDO Solution

Using PDO, the code would appear as follows:

<code class="php">$stmt = $db->prepare('CALL multiples(:param1, :param2)');
$stmt->execute([':param1' => $param1, ':param2' => $param2]);

// Fetch and process the first result set
while ($row1 = $stmt->fetch()) {
    // Process row1
}

// Advance to the second result set
$stmt->nextRowset();

// Fetch and process the second result set
while ($row2 = $stmt->fetch()) {
    // Process row2
}</code>
Copy after login

Note:

It is important to remember that not all database servers support multiple result sets from stored procedures. Always refer to your database server's documentation for compatibility.

The above is the detailed content of How to Retrieve Multiple Result Sets from Stored Procedures in MySQL with PHP/mysqli and PDO?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template