将 SQL 数据库和 PHP 移动到 Azure - 证明连接

我正在将现有的 PHP 网站和 SQL 数据库从离线测试环境迁移到 Azure。我发现很难返回以下简单查询来证明我的 Azure SQL 数据库和 Azure 托管 php 网页之间的连接。我在我的测试环境中测试了以下内容并返回了我的数据。当我在 Azure 中运行它时,仅返回标题“Name Age”。(注意:在编写 php 语句时,我无法出现 < ?php & ?> )


$serverName = "tcp:DBName.database.windows.net,1443";

$connectionOptions = array("Database" => "DBName","Uid" => "DBUser","PWD" => "DBpwd");

//Establishes the connection

$connection = sqlsrv_connect($serverName, $connectionOptions);

$tsql= "SELECT Name, Age

     FROM Person";

$query = mysqli_query($connection, $tsql);


      <tr>

        <th>Name</th>

        <th>Age</th>

      </tr>

        <tbody>

          <?php while ($row = mysqli_fetch_array($query))

          { ?>

            <tr>

              <td><?php echo $row['Name'] ?></td>

              <td><?php echo $row['Age'] ?></td>

            </tr>

          <?php } ?>

        </tbody>

    </section>

  </tbody>

在 Azure 中,我只完成了以下资源的初始设置:SQL 服务器、SQL 数据库和应用服务。我已使用名为 Person 的单个表(包含一些姓名和年龄数据)填充了我的 SQL 数据库(来自 Microsoft SQL Server Management Studio),并将包含上述代码的测试 php 页面加载到我的应用服务中。


我之前在测试环境中使用 myPHPAdmin,但我想将其移至 Azure 以使其更安全且更易于访问 - 我知道这将需要重新编写一些代码,但我想首先证明连接。我知道我错过了一些明显的东西,但任何帮助将不胜感激。


哔哔one
浏览 127回答 1
1回答

慕少森

您正在使用来自两个不同 PHP 扩展(sqlsrv_connect()和 mysqli_query()\ mysqli_fetch_array())的函数。要连接到 SQL Server,您只需要sqlsrv_函数(SQL Server 的 PHP 驱动程序的一部分)。以下脚本根据您的尝试演示了如何连接到 SQL Server 并检索数据:<?php// Connection$serverName = "tcp:DBName.database.windows.net,1443";$connectionOptions = array("Database" => "DBName", "Uid" => "DBUser", "PWD" => "DBpwd");$connection = sqlsrv_connect($serverName, $connectionOptions);if ($connection === false) {&nbsp; &nbsp; echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);&nbsp; &nbsp; exit;}&nbsp; &nbsp;// Statement$tsql = "SELECT Name, Age FROM Person";$query = sqlsrv_query($connection, $tsql);if ($query === false) {&nbsp; &nbsp; echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);&nbsp; &nbsp; exit;}&nbsp; &nbsp;?><tr>&nbsp; &nbsp; <th>Name</th>&nbsp; &nbsp; <th>Age</th></tr><tbody><?php&nbsp;// Datawhile ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)) {&nbsp;?><tr>&nbsp; &nbsp; <td><?php echo $row['Name'] ?></td>&nbsp; &nbsp; <td><?php echo $row['Age'] ?></td></tr><?php&nbsp;}&nbsp;?></tbody><?php// Endsqlsrv_free_stmt($query);sqlsrv_close($connection);?>
打开App,查看更多内容
随时随地看视频慕课网APP