Home > Article > Backend Development > How do I retrieve multiple result sets from a stored procedure using MySQLi in PHP?
Retrieving Multiple Result Sets from a Stored Procedure with MySQLi
Your stored procedure, "multiples," generates multiple result sets. To advance to and retrieve data from subsequent result sets, follow these steps using the MySQLi extension:
PHP Procedural Style:
<code class="php">// Prepare the statement $stmt = mysqli_prepare($db, 'CALL multiples(?, ?)'); // Bind parameters mysqli_stmt_bind_param($stmt, 'ii', $param1, $param2); // Execute the statement mysqli_stmt_execute($stmt); // Fetch the first result set $result1 = mysqli_stmt_get_result($stmt); while ($row1 = $result1->fetch_assoc()) { echo "Result 1: " . $row1['id'] . "\n"; } // Advance to the second result set mysqli_stmt_next_result($stmt); $result2 = mysqli_stmt_get_result($stmt); // Fetch and print the second result set while ($row2 = $result2->fetch_assoc()) { echo "Result 2: " . $row2['id'] . "\n"; } // Close the statement mysqli_stmt_close($stmt);</code>
PHP Object-Oriented Style:
<code class="php">// Create a prepared statement object $stmt = $db->prepare('CALL multiples(?, ?)'); // Bind parameters $stmt->bind_param('ii', $param1, $param2); // Execute the statement $stmt->execute(); // Fetch the first result set $result1 = $stmt->get_result(); while ($row1 = $result1->fetch_assoc()) { echo "Result 1: " . $row1['id'] . "\n"; } // Advance to the second result set $stmt->next_result(); // Store and print results from the second result set $result2 = $stmt->get_result(); while ($row2 = $result2->fetch_assoc()) { echo "Result 2: " . $row2['id'] . "\n"; } // Close the statement $stmt->close();</code>
Additional Notes:
The above is the detailed content of How do I retrieve multiple result sets from a stored procedure using MySQLi in PHP?. For more information, please follow other related articles on the PHP Chinese website!