0

I have a problem querying my MSSQL database and PHP7 I use the new Microsoft driver. I got the following error: sqlsrv_query() expects parameter 1 to be resource, null given in /var/www/html/sqlFunctions.php on line 33

If I put the 2 functions together in one function it works According to the microsft examples it should work https://learn.microsoft.com/nl-nl/sql/connect/php/step-3-proof-of-concept-connecting-to-sql-using-php

function OpenConnection()  
{  
    try  
    {  
        $serverName = "devsql1";  
        $connectionOptions = array(
            "Database"=>"test",  
            "Uid"=>"test", 
            "PWD"=>"test"
            );  
        $conn = sqlsrv_connect($serverName, $connectionOptions); 

        if($conn == false)  
            die(FormatErrors(sqlsrv_errors()));  
    }  
    catch(Exception $e)  
    {  
        echo("Error!");  
    }  
}

  function ReadData()  
{  
    try  
    {  


        $conn = OpenConnection();

        $tsql = "SELECT [Corporatienaam] FROM tbl_Corporatie";  
        $getProducts = sqlsrv_query($conn, $tsql);  
        if ($getProducts == FALSE)  
            die(FormatErrors(sqlsrv_errors()));  
        $productCount = 0;  
        while($row = sqlsrv_fetch_array($getProducts, SQLSRV_FETCH_ASSOC))  
        {  
            echo($row['Corporatienaam']);  
            echo("<br/>");  
            $productCount++;  
        }  
        sqlsrv_free_stmt($getProducts);  
        sqlsrv_close($conn);  
    }  
    catch(Exception $e)  
    {  
        echo("Error!");  
    }  
}
1
  • OpenConnection doesn't return anything, so ReadData's $conn is null. Commented Feb 21, 2017 at 16:14

1 Answer 1

1

Your function OpenConnection is not returning any value, so $conn will be null when called. This should fix it:

function OpenConnection()  
{  
    try  
    {  
        $serverName = "devsql1";  
        $connectionOptions = array(
            "Database"=>"test",  
            "Uid"=>"test", 
            "PWD"=>"test"
            );  
        $conn = sqlsrv_connect($serverName, $connectionOptions); 

        if($conn == false)  
            die(FormatErrors(sqlsrv_errors()));  
        return $conn;
    }  
    catch(Exception $e)  
    {  
        echo("Error!");  
    }  
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so obvious.
It happens, here to help.

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.