简体   繁体   中英

Connecting to an Azure MySQL Database with PHP

Here's my code to test connecting to the DB I just set up.

<?php
// DB connection info
$servername = "slateproject.database.windows.net";
$username = "";
$password = "";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>

and the error

Connection failed: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Any clue what is preventing the connection?

Your database endpoint is database.windows.net , and it is the common endpoint of Azure SQL Service which is based on SQLServer but MySQL.

To connect to SQL Server in PHP, we need to enable php_sqlsrv extension, and the connection code sample: <?php $connectionInfo = array( "UID" => "<user>@ttyir96emw", "pwd" => "<your_passwd>", "Database" => "garytestmb_db", "LoginTimeout" => 30, "Encrypt" => 1 ); $serverName = "tcp:ttyir96emw.database.windows.net,1433"; $conn = sqlsrv_connect($serverName, $connectionInfo); ?> <?php $connectionInfo = array( "UID" => "<user>@ttyir96emw", "pwd" => "<your_passwd>", "Database" => "garytestmb_db", "LoginTimeout" => 30, "Encrypt" => 1 ); $serverName = "tcp:ttyir96emw.database.windows.net,1433"; $conn = sqlsrv_connect($serverName, $connectionInfo); ?> <?php $connectionInfo = array( "UID" => "<user>@ttyir96emw", "pwd" => "<your_passwd>", "Database" => "garytestmb_db", "LoginTimeout" => 30, "Encrypt" => 1 ); $serverName = "tcp:ttyir96emw.database.windows.net,1433"; $conn = sqlsrv_connect($serverName, $connectionInfo); ?> By the way, in Azure manage portal , the DASHBORAD page, we can click “Show connection string” to check the connection string and code examples in different language.

If you want to use MySQL as database, Azure provides ClearDB as MySQL server , you can follow How to Create a MySQL Database in Azure to create a MySQL database via ClearDB.

If you want to build your MySQL database in Azure VM, please refer Install MySQL on a virtual machine created with the classic deployment model running Windows Server 2012 R2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM