I'm using Azure for a PHP web-app that is coupled to a MySQL database. We'd like to try to use the MySQL in-app option to store our data. However, I'm having difficulties connecting to the DB from PHP code. The blog post by Microsoft for connecting to the MySQL database doesn't seem to work for me.
The blog has a piece of code written that defines some global constants by parsing an environment variable. This environment variable, however, seems to have just an empty value instead of the full string of parameters to connect, i.e. "Database=localdb;Data Source=127.0.0.1:49782;User Id=azure;Password=password". I can fill in this info manually into my code to try to connect, but this isn't robust since the port of the source can change.
So my real issue lies in that the "MYSQLCONNSTR_localdb" environment variable doesn't have the right value, even after following all of the steps in the blog post. What am I missing here?
Thank you in advance!
The code I use for testing:
<?php
// From the blog-post
$connectstr_dbhost = '';
$connectstr_dbname = '';
$connectstr_dbusername = '';
$connectstr_dbpassword = '';
foreach ($_SERVER as $key => $value)
{
if (strpos($key, "MYSQLCONNSTR_") !== 0)
{
continue;
}
$connectstr_dbhost = preg_replace("/^.*Data Source=(.+?);.*$/", "\\1", $value);
$connectstr_dbname = preg_replace("/^.*Database=(.+?);.*$/", "\\1", $value);
$connectstr_dbusername = preg_replace("/^.*User Id=(.+?);.*$/", "\\1", $value);
$connectstr_dbpassword = preg_replace("/^.*Password=(.+?)$/", "\\1", $value);
echo $value;
}
define('DB_NAME', $connectstr_dbname);
define('DB_USER', $connectstr_dbusername);
define('DB_PASSWORD', $connectstr_dbpassword);
define('DB_HOST', $connectstr_dbhost);
// Custom testing
echo $connectstr_dbname."\n";
echo $connectstr_dbusername."\n";
echo $connectstr_dbpassword."\n";
echo $connectstr_dbhost."\n";
$dbConnection = $dbLink = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($dbConnection)
{
echo "Successfully connected to the database.\n";
}
else
{
echo "Failed to connect to the database.\n";
}
?>
EDIT: updated the code and removed part of the problem that was caused by a malformed if-statement thanks to @ Aaron Chen - MSFT

