Jump to content

Retrieving output parameter from SQL server stored procedure


Recommended Posts

 How to retrieve a table output parameter from sql server stored procedure to php variable? 


I've the following code that returns a table from the query. The table needs to be retrieved in PHP and formatted before being printed onto a file. 


## Stored Procedure: 


 @query1 has a table from select statement that is pivoted. 


       EXEC SP_EXECUTESQL @query= @query1, @params= N'@queryO NVARCHAR(MAX) OUTPUT', @queryO= @queryO OUTPUT; 

       declare @getProducts NVARCHAR(MAX) 
       select @getProducts= @queryO; 
## The PHP code follows: 


    $stmt2 = sqlsrv_query($conn, $tsql_createSP);
    if( $stmt2 === false )
    echo "Error in executing statement 2.\n";
    die( print_r( sqlsrv_errors(), true));
  $params = array(
  $tsql_callSP = "{call spGetPivot( ?,? OUTPUT)}";
  $stmt3 = sqlsrv_query($conn,$tsql_callSP,$params);
  if ( $stmt3 === false) { echo "Error in executing statement 3.\n";
        die( FormatErrors( sqlsrv_errors() ) );}
  $productCount = 0;     
  function cleanData($str)
    $str = preg_replace("/\t/", "\\t", $str);
    $str = preg_replace("/\r?\n/", "\\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
 // file name for download
  $filename = "NAM_data_" . date('YmdHis') ."_pg".".txt";
  header("Content-Disposition: attachment; filename=\"$filename\"");
  header("Content-Type: text/plain");
  $flag = false;
  while( $row = sqlsrv_fetch_array( $getProducts, SQLSRV_FETCH_ASSOC)){
      // display field/column names as first row
      array_walk($row, 'cleanData');
      echo implode("\t", array_keys($row)) . "\r\n";
      $flag = true;
    array_walk($row, 'cleanData');
    echo implode("\t", array_values($row)). "\r\n";
   sqlsrv_free_stmt( $stmt1);
   sqlsrv_free_stmt( $stmt2);
   sqlsrv_free_stmt( $stmt3);
   sqlsrv_close( $conn);
I'm not able to retrieve the output with this code. The query works well in this format in SSMS. 
Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.