Export (0) Print
Expand All

How to: Retrieve a Single Field

The SQL Server Driver for PHP provides the sqlsrv_get_field function for retrieving a single field of a result set row. The example in this topic demonstrates how to retrieve a row of data one field at a time.

Cc296195.note(en-US,SQL.90).gifNote:
The sqlsrv_get_field function should be used when you must specify the PHP data type of the returned data or when you must retrieve data as a stream. For more information, see Comparing Data Retrieval Functions.

The following example iterates through each row of a result set using the sqlsrv_fetch function and then iterates through each field of a row using the sqlsrv_get_field function.

The example retrieves product information from the Purchasing.PurchaseOrderDetail table of the AdventureWorks database for products that have a specified date and a stocked quantity (StockQty) less than a specified value.

The example assumes that the AdventureWorks database is installed on the server. All output is written to the console when the example is run from the command line.

<?php
/* Connect to the local server using Windows Authentication and
specify the AdventureWorks database as the database in use. */
$serverName = "(local)";
$connectionInfo = array( "Database"=>"AdventureWorks");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false )
{
     echo "Could not connect.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Define the query. */
$tsql = "SELECT ProductID,
                UnitPrice,
                StockedQty 
         FROM Purchasing.PurchaseOrderDetail
         WHERE StockedQty < 3 
         AND DueDate='2002-01-29'";

/* Execute the query. */
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt )
{
     echo "Statement executed.\n";
} 
else 
{
     echo "Error in statement execution.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Iterate through the result set, printing a row of data upon each
iteration. Note that fields must be accessed in ordinal order. */
while( sqlsrv_fetch( $stmt))
{
     echo "ProdID: ".sqlsrv_get_field($stmt, 0)."\n";
     echo "UnitPrice: ".sqlsrv_get_field($stmt, 1)."\n";
     echo "StockedQty: ".sqlsrv_get_field($stmt, 2)."\n";
     echo "-----------------\n";
}

/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>

Community Additions

Show:
© 2015 Microsoft