0

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 Answers 2

2

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!");
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You are not returning a connection from your OpenConnection function.

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

Furthermore: you should't post your credentials online.

1 Comment

Thank you so much, i will not make this mistake again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.