Retrieving multiple result sets from a stored procedure in PHP (ibm_db2)

When a single call to a stored procedure returns more than one result set, you can use the db2_next_result function of the ibm_db2 API to retrieve the result sets.

Before you begin

You must have a statement resource returned by the db2_exec or db2_execute function that has multiple result sets.

Procedure

To retrieve multiple result sets:

  1. Fetch rows from the first result set returned from the procedure by calling one of the ibm_db2 fetch functions, passing the statement resource as an argument. (The first result set that is returned from the procedure is associated with the statement resource.)
    Table 1. ibm_db2 fetch functions
    Function Description
    db2_fetch_array Returns an array, indexed by column position, representing a row in a result set. The columns are 0-indexed.
    db2_fetch_assoc Returns an array, indexed by column name, representing a row in a result set.
    db2_fetch_both Returns an array, indexed by both column name and position, representing a row in a result set
    db2_fetch_row Sets the result set pointer to the next row or requested row. Use this function to iterate through a result set.
    db2_fetch_object Returns an object with properties representing columns in the fetched row. The properties of the object map to the names of the columns in the result set.
  2. Retrieve the subsequent result sets by passing the original statement resource as the first argument to the db2_next_result function. You can fetch rows from the statement resource until no more rows are available in the result set.

    The db2_next_result function returns False when no more result sets are available or if the procedure did not return a result set.

    For more information about the ibm_db2 API, see http://www.php.net/docs.php.

Example

Retrieve multiple result sets from a stored procedure.

$stmt = db2_exec($conn, 'CALL multiResults()');

print "Fetching first result set\n";
while ($row = db2_fetch_array($stmt)) {
    // work with row
}

print "\nFetching second result set\n";
$result_2 = db2_next_result($stmt);
if ($result_2) {
  while ($row = db2_fetch_array($result_2)) {
    // work with row
  }
}

print "\nFetching third result set\n";
$result_3 = db2_next_result($stmt);
if ($result_3) {
  while ($row = db2_fetch_array($result_3)) {
    // work with row
  }
}

What to do next

When you are ready to close the connection to the database, call the db2_close function. If you attempt to close a persistent connection that you created by using db2_pconnect, the close request returns TRUE, and the persistent IBM® data server client connection remains available for the next caller.