Home  >  Article  >  Backend Development  >  How do I retrieve multiple result sets from a stored procedure using MySQLi in PHP?

How do I retrieve multiple result sets from a stored procedure using MySQLi in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-01 08:58:02709browse

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:

  • After advancing to the next result set, you must fetch and process it before moving on to the subsequent one.
  • If your stored procedure generates ints that are returned as empty strings, check the column types in your database table.
  • Consider using object-oriented style with MySQLi for a cleaner and more encapsulated code structure.

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!

Statement:
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