Created
May 2, 2021 21:24
-
-
Save DragonBe/6a9455d7b4470da55e4aa4e5875ca0f0 to your computer and use it in GitHub Desktop.
Convert an Azure Connection String for MySQL into a PDO resource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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