我在PHP中使用sqlsrv_connect
连接到MSSQL数据库。连接工作正常,我可以执行查询,但我有一个问题,其中指定返回的行计数与sqlsrv_fetch_array
while loop执行的迭代次数不同. 有人能解释一下原因吗?
这是我的代码…
// Establish a connection to the MSSQL database
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
// If there was an error format and display
die(formatErrors(sqlsrv_errors()));
}
// Set the query to the MSSQL database
$tsql = "SELECT xyz FROM db_table WHERE field = ? ORDER BY field ASC"; ***** DUMMY EXAMPLE ******
$params = array($some_value);
// Executes the query
$stmt = sqlsrv_query($conn, $tsql, $params, array( "Scrollable" => 'static' ));
// Was there an error
if ($stmt === false) {
die(formatErrors(sqlsrv_errors()));
}
$row_count = sqlsrv_num_rows($stmt);
echo "Total rows: ".$row_count."<br/>"; ****** THIS RETURNS 28463 ROWS, WHICH IS CORRECT ******
// Update the response
$response = array(0 => array("status" => "success", "value" => "connected", "records" => "0"));
// Set the row count start position
$i = 1;
// Iterate through the results
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
// Increase the processed row count
$i++;
}
echo $i; ****** THIS RETURNS 5978 ROWS, WHICH IS INCORRECT ******
最终在生产中,这将在while循环中执行一个操作,但我首先需要弄清楚为什么它不是遍历所有行。
我终于能够使这个工作,但使用for
循环而不是while
循环,加上使用SQLSRV_SCROLL_ABSOLUTE
显式定义行
for ($i=0; $i < sqlsrv_num_rows($stmt); $i++){
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC, SQLSRV_SCROLL_ABSOLUTE, $i);
// Do something here with $row data
echo "Row: ".trim($i);
}
按预期返回所有28463行。