Created
December 11, 2013 17:54
-
-
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.
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 | |
# 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