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 没有注册类 (异常来自 HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))
  • ¥15 知识蒸馏实战博客问题
  • ¥15 用PLC设计纸袋糊底机送料系统
  • ¥15 simulink仿真中dtc控制永磁同步电机如何控制开关频率
  • ¥15 用C语言输入方程怎么
  • ¥15 网站显示不安全连接问题
  • ¥15 51单片机显示器问题
  • ¥20 关于#qt#的问题:Qt代码的移植问题
  • ¥50 求图像处理的matlab方案
  • ¥50 winform中使用edge的Kiosk模式