dongshanxun6479 2017-02-21 16:12
浏览 123
已采纳

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

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://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条回答 默认 最新

  • douren9077 2017-02-21 16:16
    关注

    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!");  
        }  
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?