PHP Using SQLSRV Fetching Query Results


Example

There are 3 main ways to fetch results from a query:

sqlsrv_fetch_array()

sqlsrv_fetch_array() retrieves the next row as an array.

$stmt = sqlsrv_query($conn, $query);

while($row = sqlsrv_fetch_array($stmt)) {
    echo $row[0];
    $var = $row["name"];
    //...
}

sqlsrv_fetch_array() has an optional second parameter to fetch back different types of array: SQLSRV_FETCH_ASSOC, SQLSRV_FETCH_NUMERIC and SQLSRV_FETCH_BOTH(default) can be used; each returns the associative, numeric, or associative and numeric arrays, respectively.


sqlsrv_fetch_object()

sqlsrv_fetch_object() retrieves the next row as an object.

$stmt = sqlsrv_query($conn, $query);

while($obj = sqlsrv_fetch_object($stmt)) {
    echo $obj->field; // Object property names are the names of the fields from the query
    //...
}

sqlsrv_fetch()

sqlsrv_fetch() makes the next row available for reading.

$stmt = sqlsrv_query($conn, $query);

while(sqlsrv_fetch($stmt) === true) {
    $foo = sqlsrv_get_field($stmt, 0); //gets the first field -
}