PHP + SQL数据库Azure错误

时间:2015-10-14 12:46:57

标签: php sql-server azure azure-sql-database

我是网络开发的初学者,对PHP + SQL数据库连接有疑问并显示结果。

<?php

    ini_set('display_errors',1);
    ini_set('display_startup_errors',1);
    error_reporting(-1);

    function OpenConnection()
    {
        try
        {
            $serverName = "tcp:***,1433";
            $connectionOptions = array("Database"=>"flan",
                "Uid"=>"***", "PWD"=>"***");
            $conn = sqlsrv_connect($serverName, $connectionOptions);
            if($conn == false)
                die(FormatErrors(sqlsrv_errors()));
        }
        catch(Exception $e)
        {
            echo("Error!");
        }
    }

    function ReadData()
    {
        try
        {
            $conn = OpenConnection();
            $tsql = "SELECT * FROM tour_id";
            $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['tour_title']);
                echo("<br/>");
                $productCount++;
            }
            sqlsrv_free_stmt($getProducts);
            sqlsrv_close($conn);
        }
        catch(Exception $e)
        {
            echo("Error!");
        }
    }

    echo ReadData();
?>

结果:

  

警告:sqlsrv_query()期望参数1为resource,null给定   在D:\ home \ site \ wwwroot \ test.php第29行致命错误:致电   未定义的函数FormatErrors()在D:\ home \ site \ wwwroot \ test.php上   第31行

enter image description here

2 个答案:

答案 0 :(得分:2)

您的Openconnection()函数未返回任何内容,因此$conn始终为null

在函数中添加一个返回行,以便返回连接:

function OpenConnection()
{
    try
    {
        $serverName = "***";
        $connectionOptions = array("Database"=>"***", "Uid"=>"***", "PWD"=>"***");
        $conn = sqlsrv_connect($serverName, $connectionOptions);
        if($conn == false)
            die(FormatErrors(sqlsrv_errors()));

        return $conn; // <--- Here
    }
    catch(Exception $e)
    {
        echo("Error!");
    }
}

答案 1 :(得分:0)

您没有从OpenConnection功能返回连接。

//...
$conn = sqlsrv_connect($serverName, $connectionOptions);
if($conn == false)
    die(FormatErrors(sqlsrv_errors()));
return $conn;
//...

此外:你不应该在网上发布你的证书。