多次运行while($ row = sqlsrv_fetch_array($ result))

I am retrieving a couple of tables from a MSSQL database, which I am then running through to obtain order information from.

My code looks like this:

    while($row = sqlsrv_fetch_array($orderResult))
    {
        ......code........
        ..................
        while($statusRow = sqlsrv_fetch_array($statusResult))
        {
            ....code....
        }
        ....code....
    }

Now my problem is that after the second loop runs through, it never runs again. And I need it to run every time the first loop runs.

Is there anything I can do to reset that second loop to run again?

Thank you in advance. Any help or a push in the right direction will be very helpful.

Read about the other parameters in sqlsrv_fetch_array()

You can do something like this to reset

// reset, and get first row
$row = sqlsrv_fetch_row($result, SQLSRV_FETCH_BOTH, SQLSRV_SCROLL_FIRST);

// get second (and nth row) normally
$row = sqlsrv_fetch_row($result);

Alternatively, I think you could benefit from doing a JOIN in your query to return a single result. Merging results manually like this seems a little hackish.

are you sure your second loop got results for a second run ? maybe, if your $statusResult depents on your $row and your $row has just entries for the first loop you should insert some pseudo-entries to your db.

the second loop should refresh itself in the next "big" loop cause the whole inner block will be destroyed at the end of the big block and will be (fully) rebuild at the next entry.

I had a similar problem when calling a stored proc from a database that returned multiple result sets. I found Macek's answer didn't work for me, but another answer did:

$resultSet = array();
$isNotLastResult = true;
$i = 0;

while (!is_null($isNotLastResult))
{
    $resultSet[$i] = array();

    while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
    {
        $resultSet[$i][] = $row;
    }

    $isNotLastResult = sqlsrv_next_result($result);
    $i++;
}

print_r($resultSet);

PS: I gave you an up arrow to counteract your down arrow. You asked a question I spent quite a bit of time looking for the answer to. Good question!

Use the following to reset the pointer:

sqlsrv_fetch_array ($Res, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, -1);

Then use the same code as before to loop through the result set. sql_fetch_array appears to increment the pointer after retrieving the data. Requesting the -1 record retrieves nothing but then sets the pointer to 0 which is the first record.