PHP- Error with SQLSRV_FETCH_ASSOC & sqlsrv_fetch_array

waleed. picture waleed. · Jan 21, 2016 · Viewed 9.9k times · Source

This code I am using to download result from sql server query in excel . Connection & query works fine and I have already installed sqlsrv extensions properly. But still I am getting error like these

"Use of undefined constant SQLSRV_FETCH_ASSOC - assumed SQLSRV_FETCH_ASSOC'"
"Warning: sqlsrv_fetch_array() expects parameter 2 to be long"

I think the problem is with SQLSRV_FETCH_ASSOC. Any help would be appreciated.

  function cleanData(&$str)
  {
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

  $serverName = "********"; 
$connectionInfo = array( "Database"=>"****", "UID"=>"***", "PWD"=>"*****");
$connect = sqlsrv_connect( $serverName, $connectionInfo);

  // filename for download
  $filename = "website_data_" . date('Ymd') . ".xls";

  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: application/vnd.ms-excel");

  $flag = false;
  $query="select * from business_partners ORDER BY 1 desc";

  $result = sqlsrv_query($connect, $query) or die('A error occured: ' . sqlsrv_errors());
  while(false !== ($row = sqlsrv_fetch_array($result,SQLSRV_FETCH_ASSOC))) 
  {
    if(!$flag) {
      // display field/column names as first row
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    }**strong text**
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)) . "\r\n";
  }
  exit;

Answer

Gerald Schneider picture Gerald Schneider · Jan 21, 2016

I have no explanation why the constant wouldn't be defined while the extension is clearly loaded, but you should be able to circumvent the problem by defining it yourself.

SQLSRV_FETCH_ASSOC has the value 2, so you should just add this somewhere, at best in a file you include always:

if ( !defined( 'SQLSRV_FETCH_ASSOC' ) )
  define( 'SQLSRV_FETCH_ASSOC', 2 );

The if ( !defined() ) clause makes sure that your code doesn't break later, when the actual problem is fixed and the constant suddenly reappears.

Alternatively, if you only use it once in the file and it isn't really worth defining the constant (except for readability) you can just use the actual value as a parameter:

$row = sqlsrv_fetch_array( $result, 2 ); // 2 = SQLSRV_FETCH_ASSOC