隐藏

sqlsrv_fetch

发布:2014/7/8 23:56:42作者:管理员 来源:本站 浏览次数:1405

使结果集的下一行可读。使用 sqlsrv_get_field 读取该行的字段。

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

$stmt:与执行的语句对应的语句资源。

Cc296187.note(zh-cn,SQL.90).gif注意:
必须先执行语句,然后才能检索结果。有关执行语句的信息,请参阅 sqlsrv_query 和 sqlsrv_execute



row [可选]:在 1.1 版中添加。以下值之一,指定要在使用可滚动游标的结果集中访问的行:

  • SQLSRV_SCROLL_NEXT
  • SQLSRV_SCROLL_PRIOR
  • SQLSRV_SCROLL_FIRST
  • SQLSRV_SCROLL_LAST
  • SQLSRV_SCROLL_ABSOLUTE
  • SQLSRV_SCROLL_RELATIVE

有关这些值的详细信息,请参阅指定游标类型和选择行。在 SQL Server Driver for PHP 的 1.1 版中添加了可滚动游标支持。

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