使用Azure Web App连接到Azure数据库

时间:2019-11-22 15:07:07

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

我正在尝试使用以下代码连接到我的Azure sql数据库:

<?php
//Constants to connect with the database
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'pass');
define('DB_HOST', 'xyz-server.database.windows.net');
define('DB_NAME', 'xyz_db');
<?php

//Class DbConnect
class DbConnect
{
    //Variable to store database link
    private $con;

    //Class constructor
    function __construct()
    {

    }

    //This method will connect to the database
    function connect()
    {
        //Including the constants.php file to get the database constants
        include_once dirname(__FILE__) . '/Constants.php';

        //connecting to mysql database
        $this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

        //Checking if any error occured while connecting
        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }

        //finally returning the connection link 
        return $this->con;
    }

}

我收到此错误

Type: ErrorException
Code: 2
Message: mysqli::__construct(): (HY000/9002): The connection string may not be right. Please visit portal for references.
File: /home/site/wwwroot/blingoo/include/DbConnect.php
Line: 22

我只是从Azure开始。也许我想念一些东西。如果您可以简单地指出如何连接数据库和Web应用程序(我正在使用php文件连接到数据库),那将很棒。

2 个答案:

答案 0 :(得分:2)

在我看来,您的代码正在尝试连接到MySQL而不是MSSQL。

要连接到MSSQL,请使用以下命令:

<?php
    $serverName = "your_server.database.windows.net"; // update me
    $connectionOptions = array(
        "Database" => "your_database", // update me
        "Uid" => "your_username", // update me
        "PWD" => "your_password" // update me
    );
    //Establishes the connection
    $conn = sqlsrv_connect($serverName, $connectionOptions);
    $tsql= "SELECT TOP 20 pc.Name as CategoryName, p.name as ProductName
         FROM [SalesLT].[ProductCategory] pc
         JOIN [SalesLT].[Product] p
         ON pc.productcategoryid = p.productcategoryid";
    $getResults= sqlsrv_query($conn, $tsql);
    echo ("Reading data from table" . PHP_EOL);
    if ($getResults == FALSE)
        echo (sqlsrv_errors());
    while ($row = sqlsrv_fetch_array($getResults, SQLSRV_FETCH_ASSOC)) {
     echo ($row['CategoryName'] . " " . $row['ProductName'] . PHP_EOL);
    }
    sqlsrv_free_stmt($getResults);
?>

来源:https://docs.microsoft.com/en-us/azure/sql-database/sql-database-connect-query-php

答案 1 :(得分:0)

由于您尝试连接到 Azure SQL ,因此,如果安装了此扩展程序,则可以使用PDO_DBLIB驱动程序。参见php -m

$config = [
    'dsn' => 'dblib:host=xyz-server.database.windows.net;dbname=xyz_db',
    'user' => 'username',
    'pass' => 'password',
];

$connection = new PDO($config['dsn'], $config['user'], $config['pass']);

$sth = $connection->prepare('Your query comes here;');
$sth->execute();
$rows = $sth->fetchAll(PDO::FETCH_CLASS);

foreach ($rows as $row) {
    // Do the processing here
}