sqlsrv_fetch_array没有获得选择查询的第一行

时间:2019-10-16 02:52:30

标签: php sql-server sqlsrv

我的选择查询:

$query = "SELECT SERVER_NAME FROM AUDIT_Customer_Polling_details WHERE PRODUCT_NAME='".$product."' ";
$result = sqlsrv_query($con,$query)or die("Couldn't execute slect query".print_r(sqlsrv_errors(), true));

我的循环代码是:

if($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC) != Null){                               
   while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
   {
      echo $row['SERVER_NAME'];
      echo "\n";
   }
}

并且也尝试过此操作:

if( sqlsrv_fetch( $result ) === false) {
      die( print_r( sqlsrv_errors(), true));
}                   
while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC))
{
     echo $row['SERVER_NAME'];
     echo "\n";
}

没有任何错误。但是while循环越过了存在的第一行。

2 个答案:

答案 0 :(得分:0)

删除if条件,因为调用此if($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC) != Null)时已经获取了第一条记录

   while( $row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
   {
      echo $row['SERVER_NAME'];
      echo "\n";
   }

您可能想考虑使用它。

if($result=== true)
{
   while( $row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
   {
      echo $row['SERVER_NAME'];
      echo "\n";
   }
}

答案 1 :(得分:0)

最后我从条件中移除了代码。它工作正常。最终代码是:

 $query = "SELECT SERVER_NAME FROM AUDIT_Customer_Polling_details WHERE PRODUCT_NAME='".$product."' "; 
 $result = sqlsrv_query($con,$query)or die("Couldn't execute slect query".print_r(sqlsrv_errors(), true)); 

 while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_ASSOC)) {
      echo $row['SERVER_NAME'];
      echo "\n"; }