Share via


sqlsrv_get_field

從目前資料列的指定欄位中擷取資料。欄位資料必須依序存取。例如,當存取了第二個欄位中的資料以後,便無法存取第一個欄位中的資料。

語法

sqlsrv_get_field( resource $stmt, int $fieldIndex [, int $getAsType])

參數

$stmt:對應到執行之陳述式的陳述式資源。

$fieldIndex:要擷取之欄位的索引。索引是從零開始。

$getAsType [選擇性]:SQLSRV 常數 (SQLSRV_PHPTYPE_*),可決定傳回之資料的 PHP 資料類型。如需有關支援之資料類型的資訊,請參閱<SQLSRV 常數>。如果未指定任何傳回類型,將會傳回預設 PHP 類型。如需有關預設 PHP 類型的資訊,請參閱<預設 PHP 資料類型>。如需有關指定 PHP 資料類型的資訊,請參閱<如何:指定 PHP 資料類型>。

傳回值

欄位資料。您可以使用 $getAsType 參數來指定傳回之資料的 PHP 資料類型。如果未指定任何傳回資料類型,將會傳回預設 PHP 資料類型。如需有關預設 PHP 類型的資訊,請參閱<預設 PHP 資料類型>。如需有關指定 PHP 資料類型的資訊,請參閱<如何:指定 PHP 資料類型>。

範例

下列範例會擷取包含產品評論與評論者名稱的資料列。若要從結果集中擷取資料,則會使用 sqlsrv_get_field。此範例假設 SQL Server 和 AdventureWorks 資料庫已經安裝在本機電腦上。當從命令列執行此範例時,所有輸出都會寫入主控台。

<?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));
}

/* Set up and execute the query. Note that both ReviewerName and
Comments are of the SQL Server nvarchar type. */
$tsql = "SELECT ReviewerName, Comments 
         FROM Production.ProductReview
         WHERE ProductReviewID=1";
$stmt = sqlsrv_query( $conn, $tsql);
if( $stmt === false )
{
     echo "Error in statement preparation/execution.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Make the first row of the result set available for reading. */
if( sqlsrv_fetch( $stmt ) === false )
{
     echo "Error in retrieving row.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Note: Fields must be accessed in order.
Get the first field of the row. Note that no return type is
specified. Data will be returned as a string, the default for
a field of type nvarchar.*/
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";

/*Get the second field of the row as a stream.
Because the default return type for a nvarchar field is a
string, the return type must be specified as a stream. */
$stream = sqlsrv_get_field( $stmt, 1, 
                            SQLSRV_PHPTYPE_STREAM( SQLSRV_ENC_CHAR));
while( !feof( $stream))
{ 
    $str = fread( $stream, 10000);
    echo $str;
}

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

另請參閱

概念

比較資料擷取函數
有關文件集中的程式碼範例

其他資源

API 參考 (SQL Server Driver for PHP)
擷取資料