'sqlsrv_fetch_array function in PHP does not work

I'm using the function sqlsrv_fetch_array in a lot of pages in my website, but for some reason, in a specific case it doesn't work.

I sent the query manually, in the SQL and it works fine. Here is the result of the query I've sent:

4721    fino    [email protected]  Apr 28 2016  7:27PM 127.0.0.1   3   3   Fino Nab    MA  educ    1   1   60  NULL    Danda

The name of the variable that handles the result is $infoQuery.

When I print sqlsrv_num_rows($infoQuery), the result is 1 ( correct result ).

echo sqlsrv_num_rows( $infoQuery ); // result is 1 ( correct result )

But when I try to do that:

while( $row = sqlsrv_fetch_array( $infoQuery ) ) {
    echo "Just printing..";
}

It prints nothing, which means, it doesn't work. I'm using PHP 7, with SQL SERVER 2012, windows 7. Does anyone has an idea for why it happens?



Solution 1:[1]

Make sure you load BOTH dll's listed in the README: extension=php_sqlsrv_56_ts.dll extension=php_pdo_sqlsrv_56_ts.dll

Solution 2:[2]

I had the same issue, I used this, It fixed my problem

$conn = new PDO("sqlsrv:Server=$serverName;Database=$dbName", "$username", "$password");

$stmt = $conn->prepare("SELECT COR.CourseID AS id ");

$stmt->execute();

$ind = 0;

while ($row = $stmt->fetch()) {

  print_r($row);

}

Solution 3:[3]

May be the query answare have 2 result you must use sqlsrv_next_result() because the rows afected some times apaears like numer one in the list recordsets

Try this, only if you are sure the response have fields :

enter code here

 if ( sqlsrv_num_fields($qry_actcmd) == 0) )  // to verify if it is a record set
                sqlsrv_next_result($qry_actcmd);  //go to next result recordset.

//Now, Fetch the "real" recordset

while ($row = sqlsrv_fetch_array( $qry_actcmd, SQLSRV_FETCH_ASSOC ) )
{
  //....
}

Solution 4:[4]

Try this:

while( $row = sqlsrv_fetch_array( $infoQuery, SQLSRV_FETCH_ASSOC ) ) {
    echo "Just printing..";
}

If you will get false you can inspect the error you've got:

    foreach( sqlsrv_errors() as $error ) {
        echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
        echo "code: ".$error[ 'code']."<br />";
        echo "message: ".$error[ 'message']."<br />";
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gurjeet Singh Azad
Solution 2 user2545174
Solution 3 Asdrug
Solution 4