Share via


sqlsrv_fetch

讓結果集的下一個資料列可供讀取。使用 sqlsrv_get_field 可讀取資料列的欄位。

語法

sqlsrv_fetch( resource $stmt[, row[, ]offset])

參數

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

注意

在可以擷取結果之前必須先執行陳述式。如需有關執行陳述式的資訊,請參閱<sqlsrv_query>和<sqlsrv_execute>。

row [選擇性]:在 1.1 版中新增。下列其中一個值,指定要在使用可捲動資料指標的結果集中存取的資料列:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

如需有關這些值的詳細資訊,請參閱<指定資料指標類型和選取資料列>。SQL Server Driver for PHP 1.1 版新增了可捲動資料指標的支援。

offset [選擇性]:搭配 SQLSRV_SCROLL_ABSOLUTE 和 SQLSRV_SCROLL_RELATIVE 使用,以便指定要擷取的資料列。結果集中的第一個記錄是 0。

傳回值

如果已成功擷取結果集的下一個資料列,便會傳回 true。如果結果集中沒有其他結果,便會傳回 null。如果發生錯誤,就會傳回 false

範例

下列範例會使用 sqlsrv_fetch 來擷取包含產品評論與評論者名稱的資料列。若要從結果集中擷取資料,則會使用 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 SQL Server type nvarchar. */
$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)