I have recently switched a PHP app from mssql to sqlsrv and would like to continue using a couple custom functions to handle all my SQL requests. I get an error
Warning: sqlsrv_fetch_array(): 2 is not a valid 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);
?>
You should declare $conn
variable as global or try to fetch data inside tko_query
function body. When tko_query
ends the connection is closed and you cannot fetch data..