I have a PHP application that needs to remotely connect to a HEROKU app's postgresql database and run database queries (preferably using pg_query, though PDO is ok too). I am stuck trying to 1.) obtain live db credentials using the Heroku DATABASE_URL (as they recommend), and 2) generate any kind of db connection even when hard-coded credentials are supplied. I haven't found the proper sequence of steps to make a connection. (App is running on GoDaddy hosting - mentioned for clarity.)
I am trying to connect to the database, run a select query and assign the values from the resultset to PHP variables. I can connect to the database using PGAdmin3 so remote access isn't the issue.
What I have so far (Edited- commented lines are from original post):
//$DATABASE_URL='$({heroku CLI string, pasted from Heroku db credentials page})';
//$db = parse_url(getenv($DATABASE_URL));
$db_url = getenv("DATABASE_URL") ?: "postgres://user:pass@host:port/dbname";
$db = pg_connect($db_url);
if($db) {echo "connected";} else {echo "not connected";}
$selectSql = "SELECT id, name FROM companies ORDER BY id";
$result = pg_query($db, $selectSql);
while ($row = pg_fetch_row($result)) {
$id = $row["id"];
$name = $row["name"];
echo "<br>id: ".$id;
echo "<br>name: ".$name;
}
What is missing to connect to the database and run queries?