Skip to content

Instantly share code, notes, and snippets.

@karloscarweber
Created December 11, 2013 17:54
Show Gist options
  • Save karloscarweber/7915228 to your computer and use it in GitHub Desktop.
Save karloscarweber/7915228 to your computer and use it in GitHub Desktop.
This function reads your DATABASE_URL config var and returns a connection string suitable for pg_connect on Heroku.
<?php
# This function reads your DATABASE_URL config var and returns a connection
# string suitable for pg_connect. Put this in your app.
function pg_connection_string_from_database_url() {
extract(parse_url($_ENV["DATABASE_URL"]));
return "user=$user password=$pass host=$host dbname=" . substr($path, 1); # <- you may want to add sslmode=require there too
}
# Here we establish the connection. Yes, that's all.
$pg_conn = pg_connect(pg_connection_string_from_database_url());
# Now let's use the connection for something silly just to prove it works:
$result = pg_query($pg_conn, "SELECT relname FROM pg_stat_user_tables WHERE schemaname='public'");
print "<pre>\n";
if (!pg_num_rows($result)) {
print("Your connection is working, but your database is empty.\nFret not. This is expected for new apps.\n");
} else {
print "Tables in your database:\n";
while ($row = pg_fetch_row($result)) { print("- $row[0]\n"); }
}
print "\n";
# found at: https://github.com/kch/heroku-php-pg
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment