Skip to content
Advertisement

How to use Mysql Connection String inside PHP code which is served by Azure Lunix App Service

I’m trying to host WordPress to Azure lunix App service.

I created a Azure Database for MySQL, then I got the web app connection string from the connection strings screen.

Azure Database for MySQL Connection Strings

The connection string format is

Database={your_database}; Data Source={data_source}; User Id= {user_id}; Password={your_password}

Then I created a Linux based app service and added the MySQL connection string to its configuration.

App service Configuration

Then I used this code in wp-config.php to get the Database connection string form the PHP environment variable MYSQLCONNSTR_bridgesConnection

<?php

$connectstr_dbhost = '';
$connectstr_dbname = '';
$connectstr_dbusername = '';
$connectstr_dbpassword = '';

foreach ($_SERVER as $key => $value) {
    echo $key ;
 if (strpos($key, "MYSQLCONNSTR_bridgesConnection") !== 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);
}

That code works if you are using windows App service. But If you are using Linux App service you will get this warning and the wordpress won’t work

Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /wordpress/wp-includes/wp-db.php on line 1452

I created a php info page using this code

<?php
phpinfo();
?>

I’m sure that the PHP environment variable is loaded but I need a way to access it.

PHP info page

How to access that connection string in PHP code?

Advertisement

Answer

After very long search I found the only way to do that is to use getenv function.

The final code in wp-config.php would be:

$connectstr_dbhost = '';
$connectstr_dbname = '';
$connectstr_dbusername = '';
$connectstr_dbpassword = '';

$value = getenv('MYSQLCONNSTR_bridgesConnection');

 $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);


// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', $connectstr_dbname);

/** MySQL database username */
define('DB_USER', $connectstr_dbusername);

/** MySQL database password */
define('DB_PASSWORD', $connectstr_dbpassword);

/** MySQL hostname : this contains the port number in this format host:port . Port is not 3306 when using this feature*/
define('DB_HOST', $connectstr_dbhost);
Advertisement