"***", "PWD"=>"***"); -6ren">
gpt4 book ai didi

PHP + SQL 数据库 Azure 错误

转载 作者:行者123 更新时间:2023-12-03 06:00:10 29 4
gpt4 key购买 nike

我是一名 Web 开发初学者,对 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

enter image description here

最佳答案

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

关于PHP + SQL 数据库 Azure 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33125743/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com