0

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?

6
  • return $stmt; missing the variable symbol Commented Nov 12, 2014 at 22:13
  • @Mihai Thanks, I corrected that, but the code still behaves the same. Commented Nov 12, 2014 at 22:14
  • 1
    Could be a scope issue. Try passing $dbc to your function, or (not recommended) to make it global $dbc; in your function. Commented Nov 12, 2014 at 22:16
  • @Fred-ii- That seems to have fixed it. Write this as an answer and I'll vote it up and mark it as correct. Thanks for your help! Commented Nov 12, 2014 at 22:19
  • Will do and you're welcome Joel. Commented Nov 12, 2014 at 22:20

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I was able to use what you deemed the best method of passing in the $dbc.
@JoelTrauger That's great Joel, it is better. global is thought of as being "evil", so they say. It has its pros & cons.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.