PHP与sqlsrv_num_rows

时间:2011-08-11 20:15:27

标签: php database sql-server-2008

我正在尝试执行SQL Server数据库的查询,查看多对多关系。我将我希望行的表与关系表链接起来,并插入唯一的id,在本例中是$ guid。

有时,查询功能正常。它会起作用,然后我只将$ guid切换到另一个,它失败了,即使我正盯着桌子,它有与新的$ guid相关的值。

<?php
$guid = '{893C7BF8-E8C5-41D5-9C61-A72CF62DDBA8}';

// Connect to Database
$server = "#@#($#";     
$connectionSettings = array("Database"=>"db", "UID"=>"user", "PWD"=>"pword");
$connection = sqlsrv_connect($server, $connectionSettings);

if (!$connection){
    die("Failed Connection");
}

// Prepare and Execute Query
$sql = "SELECT * 
        FROM STREAMS.ATTACHMENTS a INNER JOIN STREAMS.RELATTACHMENTS ra
        ON a.ROWGUID = ra.ATTACHMENT_GUID
        WHERE ra.FEATURE_GUID = '" . $guid . "'";

$results = sqlsrv_query($connection, $sql);
$rowCount = sqlsrv_num_rows( $results );

if ($rowCount === false)
    echo "failure";
else
    echo $rowCount;

while($row = sqlsrv_fetch_array($results)){
    echo "loop";
}
?>

更奇怪的是,此代码的输出如下:

failurelooploop

这意味着sqlsrv_num_rows命令不计算结果中的行...但它也意味着相同的结果集有2行,因为while循环大约两次。

有人可以解释这种时髦的行为吗?

感谢。

2 个答案:

答案 0 :(得分:3)

我敢打赌你有一些错误:如果出现问题,sqlsrv_num_rows会返回FALSE。您可以通过以下方式获取错误输出:

// probably don't want this in production.
print_r( sqlsrv_errors());

我猜原因与你的guid专栏有关,但我无法确定。 : - )

哦,除非你需要行数,否则不要使用它。请改用do... while

$row = sqlsrv_fetch_array($results);
if($row)
{
    do{
        echo "loop";
    } while( $row = sqlsrv_fetch_array( $results ) );
}
else
{
    // No results found
    // you can output print_r( sqlsrv_errors() ); here
}

答案 1 :(得分:0)

此错误显示游标类型SQLSRV_CURSOR_FORWARD&amp; SQLSRV_CURSOR_DYNAMIC。我个人的偏好是不使用它。如果你仍然想使用它传递额外的参数来查询函数,如:

$stmt = sqlsrv_query( $connection, $sql, array(), array( "Scrollable" => 'keyset' ));
// $stmt = sqlsrv_query( $connection, $sql, array(), array( "Scrollable" => 'dynamic' ));
// $stmt = sqlsrv_query( $connection, $sql, array(), array( "Scrollable" => 'static' ));

查看更多内容:https://msdn.microsoft.com/en-us/library/hh487160.aspx - http://php.net/manual/en/function.sqlsrv-query.php