sqlsrv_fetch

PHP ドライバーのダウンロード

結果セットの次の行を読み取り可能にします。 sqlsrv_get_field を使用して、行のフィールドを読み取ります。

構文

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

パラメーター

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

注意

結果を取得するには、ステートメントを実行する必要があります。 ステートメントを実行する方法の詳細については、「 sqlsrv_query 」と「 sqlsrv_execute」を参照してください。

row [省略可能]: 次の値のいずれかであり、スクロール可能なカーソルを使用する結果セットでアクセスする行を指定します。

  • SQLSRV_SCROLL_NEXT

  • SQLSRV_SCROLL_PRIOR

  • SQLSRV_SCROLL_FIRST

  • SQLSRV_SCROLL_LAST

  • SQLSRV_SCROLL_ABSOLUTE

  • SQLSRV_SCROLL_RELATIVE

これらの値の詳細については、「 カーソルの種類を指定し、行を選択する」を参照してください。

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);  
?>  

参照

データの取得

SQLSRV ドライバー API リファレンス

ドキュメントのコード例について