Joel Trauger
Joel Trauger

Reputation: 732

Trouble returning MSSQL query results from PHP function

I'm getting a strange error when attempting to return the results of a working sqlsrv_query function call.

I have set up:

function test($someinput, &$someoutput)
{
  //set up $dbc and $dbcOptions
  //generate tsql
  $params = array();
  $stmt = sqlsrv_query($dbc, $tsql, $params, $dbcOptions);
  $someoutput = $stmt;
  return $stmt;
}

$outputvar;
$results = test($inputvar, $outputvar);

//---ERROR being thrown here
$rows = sqlsrv_num_rows($results);
//$rows2 = sqlsrv_num_rows($outputvar);
//---ERROR being thrown here

In both lines (doesn't matter which I use), I'm getting an error in my php-errors.log file saying

PHP Warning:  sqlsrv_num_rows(): 2 is not a valid ss_sqlsrv_stmt resource in
E:\inetpub\wwwroot\directory\searchtest.php on line 58

which searchtest.php is the file I'm working on and line 58 is where I have the error-producing code.

Why can I not pass query results from a function like this?

Upvotes: 0

Views: 111

Answers (2)

Funk Forty Niner
Funk Forty Niner

Reputation: 74232

As per OP's wish to mark as answered, comment (slightly modified) to answer:

This sounds be a scope issue.

Try passing $dbc to your function (best), or (not recommended) to make it global $dbc; in your function.

Upvotes: 1

Christian D.
Christian D.

Reputation: 65

It looks to me, that you have an error in your SQL statment. You can call sqlsrv_errors after:

$stmt = sqlsrv_query($dbc, $tsql, $params, $dbcOptions);

if( $stmt === false ) {
    if( ($errors = sqlsrv_errors() ) != null) {
        foreach( $errors as $error ) {
            echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />";
            echo "code: ".$error[ 'code']."<br />";
            echo "message: ".$error[ 'message']."<br />";
        }
    }
}

Then you should find the error.

Upvotes: 0

Related Questions