# Converting Postgres Connection to MySQL

**URL:** <https://www.phphelp.com/t/converting-postgres-connection-to-mysql/32746>\
**Category:** General Database (Oracle, SQL Server, etc)\
**Created:** [November 2, 2020, 2:39pm UTC](https://www.phphelp.com/t/converting-postgres-connection-to-mysql/32746 "2020-11-02T14:39:02Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![hobbyist](https://www.phphelp.com/letter_avatar_proxy/v4/letter/h/5f8ce5/32.png) [@hobbyist](https://www.phphelp.com/u/hobbyist)\
**Post date:** [November 2, 2020, 2:39pm UTC](https://www.phphelp.com/t/converting-postgres-connection-to-mysql/32746/1 "2020-11-02T14:39:02Z")

</div>

Hello,

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.

```
<?php

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(
                "host=%s;port=%s;user=%s;password=%s;dbname=%s",
                $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;
}

}
```

---

<div class="post-metadata">

**Author:** ![skawid](https://www.phphelp.com/letter_avatar_proxy/v4/letter/s/bbe5ce/32.png) [@skawid](https://www.phphelp.com/u/skawid)\
**Post date:** [November 2, 2020, 8:03pm UTC](https://www.phphelp.com/t/converting-postgres-connection-to-mysql/32746/2 "2020-11-02T20:03:31Z")

</div>

Have you considered installing postgres locally and using that?
