共用方式為


sqlsrv_num_fields

擷取使用中結果集內的欄位數。請注意,可以在任何備妥的陳述式上呼叫 sqlsrv_num_fields (執行前或執行後)。

語法

sqlsrv_num_fields( resource $stmt)

參數

$stmt:目標結果集為使用中狀態的陳述式。

傳回值

代表使用中結果集內之欄位數的整數值。如果發生錯誤,就會傳回布林值 false

範例

下列範例會執行一個查詢,此查詢會從 Adventureworks 資料庫的 HumanResources.Department 資料表內擷取前三個資料列的所有欄位。sqlsrv_num_fields 函數會決定結果集內的欄位數。如此可藉由逐一查看每個傳回之資料列中的欄位來顯示資料。

此範例假設 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));
}

/* Define and execute the query. */
$tsql = "SELECT TOP (3) * FROM HumanResources.Department";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false)
{
     echo "Error in executing query.\n";
     die( print_r( sqlsrv_errors(), true));
}

/* Retrieve the number of fields. */
$numFields = sqlsrv_num_fields( $stmt );

/* Iterate through each row of the result set. */
while( sqlsrv_fetch( $stmt ))
{
     /* Iterate through the fields of each row. */
     for($i = 0; $i < $numFields; $i++)
     {
          echo sqlsrv_get_field($stmt, $i, 
                   SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_CHAR))." ";
     }
     echo "\n";
}

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

另請參閱

參考

sqlsrv_field_metadata

概念

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

其他資源

API 參考 (SQL Server Driver for PHP)