Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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