PHP + SQL 数据库 Azure 错误

PHP + SQL Database Azure error

我是网络开发的初学者,对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();
?>

结果:

Warning: sqlsrv_query() expects parameter 1 to be resource, null given in D:\home\site\wwwroot\test.php on line 29 Fatal error: Call to undefined function FormatErrors() in D:\home\site\wwwroot\test.php on line 31

您的 Openconnection() 函数没有 returning 任何东西,所以 $conn 将永远是 null.

像这样在函数中添加 return 行到 return 连接:

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

您没有从 OpenConnection 函数返回连接。

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

此外:您不应该 post 您的在线凭据。