次の方法で共有


sqlsrv_get_field

現在の行の指定したフィールドからデータを取得します。フィールドのデータには、順番にアクセスする必要があります。たとえば、2 番目のフィールドのデータにアクセスしてから、最初のフィールドのデータにアクセスすることはできません。

構文

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

パラメータ

$stmt: 実行されるステートメントに対応するステートメント リソース。

$fieldIndex: 取得するフィールドのインデックス。インデックスは 0 から始まります。

$getAsType [オプション]: 返されるデータの PHP データ型を決定する SQLSRV 定数 (SQLSRV_PHPTYPE_*)。サポートされるデータ型の詳細については、「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)
データの取得