Skip to content

Instantly share code, notes, and snippets.

@DragonBe
Created May 2, 2021 21:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DragonBe/6a9455d7b4470da55e4aa4e5875ca0f0 to your computer and use it in GitHub Desktop.
Save DragonBe/6a9455d7b4470da55e4aa4e5875ca0f0 to your computer and use it in GitHub Desktop.
Convert an Azure Connection String for MySQL into a PDO resource
<?php
declare(strict_types=1);
/**
* Example usage:
*
* $connString = 'Database=localdb;Data Source=127.0.0.1:12345;User Id=dbuser;Password=$3cR37!';
* $pdo = azureConnectionStringToPdo($connString);
*/
/**
* Converts an Azure Connection String into a PDO
* resource.
*
* @param string $connectionString
* @return PDO
* @throws PDOException
*/
function azureConnectionStringToPdo(string $connectionString): PDO
{
$connArray = explode(';', $connectionString);
$connItems = [];
foreach ($connArray as $pair) {
list ($key, $value) = explode('=', $pair);
$connItems[$key] = $value;
}
list ($host, $port) = explode(':', $connItems['Data Source']);
$dsn = sprintf(
'mysql:host=%s;port=%d;dbname=%s',
$host, $port, $connItems['Database']
);
return new PDO($dsn, $connItems['User Id'], $connItems['Password']);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment