Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

Connect to Postgres on Heroku using DATABASE_URL Config Var with PHP and PDO


Unfortunately PHP's PDO constructor doesn't take a database connection url (in a format that Heroku makes available as a config var) as an argument. It has its own, rather odd syntax.

However, it's easy enough to extract url parts with the parse_url method and work with those. This lets us work with each part as a variable for use in the PDO constructor.

So here is a snippet using the DATABASE_URL config var if present.. otherwise use our local development environment database connection.

$db = (function(){
    $parts = (parse_url(getenv('DATABASE_URL') ?: 'postgresql://username:password@localhost:5432/your_database_name_here'));
    $path = ltrim($path, "/");
    return new PDO("pgsql:host={$host};port={$port};dbname={$path}", $user, $pass);

I used a function here because extract will create variables that I do not want polluting global scope. Using this syntax keeps extracted variables isolated to the function they are called in.. (function(){})();

Also, you will have to change the database info for you local connection.. I have hard coded it in this example.

Tagged w/ #php #pdo #heroku #deployment #database #postgres #development #environments