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