共用方式為


如何:將字元資料當做資料流來擷取

SQL Server Driver for PHP 會利用 PHP 資料流來從伺服器擷取大量資料。本主題的範例示範如何將字元資料當做資料流來擷取。

範例

下列範例會從 AdventureWorks 資料庫的 Production.ProductReview 資料表擷取資料列。傳回之資料列的 Comments 欄位是使用 fpassthru 函數來當做資料流擷取及顯示。

如果要完成將資料當做資料流擷取的工作,請搭配指定為字元資料流的傳回類型使用 sqlsrv_fetchsqlsrv_get_field。此傳回類型是使用 SQLSRV_PHPTYPE_STREAM 常數所指定。如需有關 sqlsrv 常數的資訊,請參閱<SQLSRV 常數>。

此範例假設 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 the Transact-SQL query. */
$tsql = "SELECT ReviewerName, 
               CONVERT(varchar(32), ReviewDate, 107) AS [ReviewDate],
               Rating, 
               Comments 
         FROM Production.ProductReview 
         WHERE ProductReviewID = ? ";

/* Set the parameter value. */
$productReviewID = 1;
$params = array( $productReviewID);

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

/* Retrieve and display the data. The first three fields are retrieved
as strings and the fourth as a stream with character encoding. */
if(sqlsrv_fetch( $stmt ) === false )
{
     echo "Error in retrieving row.\n";
     die( print_r( sqlsrv_errors(), true));
}

echo "Name: ".sqlsrv_get_field( $stmt, 0 )."\n";
echo "Date: ".sqlsrv_get_field( $stmt, 1 )."\n";
echo "Rating: ".sqlsrv_get_field( $stmt, 2 )."\n";
echo "Comments: ";
$comments = sqlsrv_get_field( $stmt, 3, 
                             SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_CHAR));
fpassthru($comments);

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

因為前三個欄位並未指定任何 PHP 傳回類型,所以每一個欄位都會根據它的預設 PHP 類型來傳回。如需有關預設 PHP 資料類型的資訊,請參閱<預設 PHP 資料類型>。如需有關如何指定 PHP 傳回類型的資訊,請參閱<如何:指定 PHP 資料類型>。

另請參閱

概念

有關文件集中的程式碼範例

其他資源

擷取資料
將資料當做資料流擷取