sqlsrv_has_rows() doesn't roll back statement cursor correctly


Hi, sqlsrv_has_rows() function seems to interfere with the statement cursor position; assuming to work with an SQL statement wich retrieves a single record (e.g.: SELECT myField FROM myTable WHERE myIDField = someExistingValue), try this:
$stmt = sqlsrv_query($conn,$sql);
if (sqlsrv_has_rows($stmt)) {
    while ($row = sqlsrv_fetch_array($stmt)) {
        echo "first field value: " . $row[0];
// no output will be produced, because the while cycle will be never entered:
Also repeated calls passing the same (populated) statement fatally makes the returned value change from TRUE to FALSE. Assuming again to work with an SQL statement wich retrieves a single record, try this:
$stmt = sqlsrv_query($conn,$sql);
echo "<br>Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "<br>";
echo "<br>Rows?" . (sqlsrv_has_rows($stmt) ? " Yes!" : " NO!") . "<br>";
// the output will be:
// Rows? Yes!
// Rows? No!
thanks in advance


robertjohnson wrote Jan 9, 2014 at 9:24 AM

It's a bug, it only works properly when called once and once-only per result.

Internally sqlsrv_has_rows simply calls sqlsrv_fetch, so you can do the same.

If you open a scrollable cursor, you can rewind it. If it's a forward cursor, just remember that you fetched the first row.