我试图在业余时间学习PHP,并使用前端作为内部MS SQL DB,我们已经将其作为一个快速学习项目。我已经准备好了查询,但它永远不会返回任何行。我已经验证了,当连接用户返回预期的26个结果(通过Powershell和SSMS)时执行查询,并且能够在php脚本中为每个数据库提取并显示最后的备份作业,以便权限,驱动程序和查询都被排除了。尝试sqlsrv_fetch($stmt)
或sqlsrv_fetch_array($stmt)
都返回false(正如没有行时所预期的那样)。我可能过于简单了吗?
代码
$ConnectionInfo = array( "Database"=>"NetworkInfo", "UID"=>$UID, "PWD"=>$PWD);
$conn = sqlsrv_connect( $Instance, $ConnectionInfo);
if( $conn ) {
echo "Connection established to $Instance. <br />";
}
else{
echo "Connection could not be established. <br />";
print_r($ConnectionInfo);
die( print_r( sqlsrv_errors(), true));
}
echo '<br />';
$SQL_String= "USE NetworkInfo
SELECT DISTINCT dbo.site.name AS Site,
dbo.site.colloquial_name AS 'Colloquial Name',
dbo.site.former_name AS 'Former Name',
dbo.hrlocation.location_datis AS 'HR Site',
dbo.site.address AS Address,
dbo.site.city AS City,
dbo.site.state AS State,
dbo.site.zip AS ZIP,
dbo.site.main_line AS 'Main Line',
dbo.site.main_ext AS 'Main Ext'
FROM dbo.site
JOIN dbo.hrlocation ON dbo.site.id = dbo.hrlocation.site_id";
$stmt = sqlsrv_query( $conn, $SQL_String);
echo '<h3>$stmt</h3>';
echo 'Var_dump:';
$dump = var_dump($stmt);
echo '<br />';
if( $stmt === false ) {
echo "Error in statement preparation/execution.\n";
die( print_r( sqlsrv_errors(), true));
}
else {
echo 'Returned type: ' . gettype($stmt) . '<br />';
echo 'Returned rows: True' . sqlsrv_has_rows($stmt) . '<br />';
echo 'Number of rows: ' . sqlsrv_num_rows($stmt) . '<br />';
}
输出
Connection established to server.
$stmt
Var_dump:resource(3) of type (SQL Server Statement)
Returned type: resource
Returned # rows:
答案 0 :(得分:0)
这个问题实际上是双重的。
首先,使用SQL USE
导致了一个问题,但我仍然不确定为什么。从查询中删除USE NetworkInfo
会返回预期结果。
其次,sqlsrv_num_rows()的文档清楚地说明需要使用静态或键集游标创建语句资源。将资源创建调整为$stmt = sqlsrv_query( $conn, $SQL_String, array(), array("Scrollable"=>'keyset'));
可以解决问题。