sqlsrv_num_fields

アクティブな結果セット内のフィールドの数を取得します。sqlsrv_num_fields は、準備された任意のステートメントの実行の前後に呼び出すことができます。

構文

sqlsrv_num_fields( resource $stmt)

パラメータ

$stmt: 対象の結果セットがアクティブなステートメント。

戻り値

アクティブな結果セット内のフィールドの数を表す整数値。エラーが発生した場合は、ブール値 false が返されます。

次の例では、Adventureworks データベースの HumanResources.Department テーブルの最初の 3 つの行のすべてのフィールドを取得するクエリを実行します。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)