无法使用PHP7 + Microsoft驱动程序查询MSSQL数据库

时间:2017-02-21 16:12:53

标签: php sql sql-server

我在查询我的MSSQL数据库和PHP7时遇到问题我使用新的Microsoft驱动程序。 我收到以下错误: sqlsrv_query()期望参数1为资源,在第33行的/var/www/html/sqlFunctions.php中给出null

如果我将2个功能放在一个功能中就行了 根据微软的例子,它应该工作 https://docs.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 个答案:

答案 0 :(得分:1)

您的函数OpenConnection未返回任何值,因此$conn在调用时将为null。这应该解决它:

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!");  
    }  
}