Converting Postgres Connection to MySQL


I’m sorry to bother you with my newbie question. I’m going to need the help of someone to convert the following Postgres DB connection to MySQL and what line of code I might need to change in other pages. The connection was written for a Heroku app Postgres DB connection and I need to test the app locally and make some changes. Thank you.


namespace lib\db;

use Exception;
use PDO;
use PDOException;

 * Provides a reusable PDO connection
class Connection {

 * @var \PDO
private static $pdo;

 * Connect to the database and return a PDO.
 * @return PDO A PDO that can be used to interact with the database.
 * @throws Exception
static function get_db_pdo(): PDO
    if (isset(self::$pdo)) {
        return self::$pdo;

    // Get the database URL from the environment
    $url = getenv("DATABASE_URL");
    if (!$url) {
        throw new Exception('Cannot connect to the database (1)');
    $db = parse_url($url);
    if(!$db || empty($db["path"])) {
        throw new Exception('Failed to connect to database (2)');
    $db["path"] = ltrim($db["path"], "/");

    // Connect to the database
    try {
        // Data Source Name (DSN)
        $dsn = "pgsql:" . sprintf(
                $db["host"], $db["port"], $db["user"], $db["pass"], $db["path"]

        // PHP Data Object (PDO)
        self::$pdo = new PDO($dsn);
        self::$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        throw new Exception('Failed to initialize database connection (3)', 0, $e);

    return self::$pdo;


Have you considered installing postgres locally and using that?

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service