duancai7002 2015-10-14 12:46
浏览 58
已采纳

PHP + SQL数据库Azure错误

I am a beginner of web developing and have a question about the PHP + SQL Database connection and displaying the result.

<?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();
?>

Result :

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

enter image description here

  • 写回答

2条回答 默认 最新

  • duanke1286 2015-10-14 12:54
    关注

    Your Openconnection() function is not returning anything, so $conn will always be null.

    Add a return line in your function like so to return the connection:

    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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀