sql server - PHP sqlsrv: passing a resource from a function -


php 5.4.14 sql server 2012/sql client 2012 windows 2008 r2

i have function (simplified version follows) call run sql query. works correctly: connects db; runs query , obtains valid resource. problem resource gets returned null...

function squeal($query) {      $servername     = "xxxxxxxx\sqlexpress";     $uid            = "private";     $pwd            = "private";     $connectioninfo = array( "uid"=>$uid, "pwd"=>$pwd, "database"=>"dbname");      /* connect using sql server authentication. */     $conn = sqlsrv_connect( $servername, $connectioninfo);     if( $conn === false ) {          echo "unable connect.</br>";          die( print_r(sqlsrv_errors(), true));     }     /* run query */     $result = sqlsrv_query( $conn, $query, array(), array("scrollable"=>"buffered"));     if( $result === false ) {          echo "error in executing query.</br>";          die( print_r(sqlsrv_errors(), true));     }     /* check resource exists debug (still fails without these lines) */     echo("resource=".intval($result)."</br>");     echo("has rows=".sqlsrv_has_rows($result)."</br>");      return $result; }  $tsql = "select id mytable"; $fred = squeal($tsql);  echo("resource=".intval($fred)."</br>"); echo("has rows=".sqlsrv_has_rows($fred)."</br>"); 

it gives following output...

resource=8 has rows=1 resource=8  warning: sqlsrv_has_rows(): 8 not valid ss_sqlsrv_stmt resource in <path> on line 85 has rows= 

sql working correctly , returns valid resource. on return function knows has been passed resource #8 (in instance) empty. use similar method mysql works perfectly. whole intranet app relies on being able call function run query , resource back.

does resource 'die' on leaving function in sqlsvr/odbc? surely not.

i have spent couple of days scouring google answers can sql server work outside of function. appreciate suggestions

cheers

i found fascinating problem, , while searching possible cause found this topic sounds plausible.

in short: open connection resource $conn within function scope. such makes sense destroyed when leaving scope. resources stemming connection resource such automatically no longer valid, explains why query resource dies upon exiting scope. if @ way makes sense - how can derived resource continue exist without logical parent resource. we're spoilt php doesn't care this, in c#/java etc. it's plausible behaviour.

if assumption correct, simplest solution put global $conn; @ beginning of squeal function cannot out of scope. depending on rest of code implement more elegant (and less potentially conflicting) solution, implementation isn't kosher anyway connects within function , expects followups survive outside.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -