"Invalid ss_sqlsrv_stmt resource error" when trying to use php function to return sqlsrv_query result

I recently switched my PHP application from mssql to sqlsrv and would like to continue using several custom functions to handle all of my SQL queries. I get an error

Warning: sqlsrv_fetch_array (): 2 invalid ss_sqlsrv_stmt resource in ...

when using the following function to handle all sqlsrv_query () calls:

<?php function tko_query($sql) { //Check for db connection $serverName = "server\sqlexpress"; $connectionInfo = array( "Database"=>"db", "UID"=>"uid", "PWD"=>"pwd"); $conn = sqlsrv_connect( $serverName, $connectionInfo ); if( $conn === false ) { die( print_r( sqlsrv_errors(), true)); } return sqlsrv_query($conn,$sql, array(), array('Scrollable' => 'buffered')); } $sql = "SELECT * FROM jobs"; $stmt = tko_query($sql); while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) { echo $row['name']."<br />"; } sqlsrv_free_stmt( $stmt); ?> 
+4
source share
1 answer

You should declare the $conn variable global, or try to extract data inside the body of the tko_query function. When tko_query ends, the connection is closed and you cannot retrieve data.

0
source

Source: https://habr.com/ru/post/1486446/


All Articles