sqlsrv_get_field
从当前行中的指定的字段检索数据。必须按顺序访问字段数据。例如,无法在访问了第二个字段中的数据之后再回过头来访问第一个字段中的数据。
语法
sqlsrv_get_field( resource $stmt, int $fieldIndex [, int $getAsType])
参数
$stmt:与执行的语句对应的语句资源。
$fieldIndex:要检索的字段的索引。索引从零开始。
$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);
?>