27 February 2017

Azure and MySql in App for PHP connections


Microsoft Azure will provide an instance of MySql with a web application without the need to use ClearDB nor a dedicated MySql server. It's one database instance that is not really meant for high production needs.

This is great for using it with Joomla or WordPress. It's also good for developing or deploying PHP-based applications that utilize MySql.

The issue is with setting your PHP application to connect to the database. You do not create a database when using this option, you use the database that is provided and you have to connect to that database.

Here is some code to establish that database connection:

<?php

// Azure MySql Connection Strings

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

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

// DB connection info
$host = $connectstr_dbhost;
$user = $connectstr_dbusername;
$pwd = $connectstr_dbpassword;
$db = $connectstr_dbname;

....

?>

If you are configuring WordPress, you would setup like this:

define('DB_NAME', $connectstr_dbname);
define('DB_USER', $connectstr_dbusername);
define('DB_PASSWORD', $connectstr_dbpassword);
define('DB_HOST', $connectstr_dbhost);


You run the first part of the code to define the connection strings for the db_host, database, username, and password. You then use those variables to assign them to the variables of your PHP code, or use them directly.

You can alter this to define the variables with the names that your PHP code uses and use them in the for foreach statement, eliminating the 'DB Connection' section of this code.


No comments:

Post a Comment