Chartjs-How do I connect to a PostgreSQL database on Heroku server and use Chart.js?

0👍

First, you have to create a connection string from the Heroku DATABASE_URL environment variable.

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
}

In order to establish a connection with the DB, you can use pg_connect() which is a built-in function in PHP.

$conn_str = pg_connection_string_from_database_url();
$pg_conn = pg_connect($conn_str);

After successfully connecting to the DB, you can run the queries as you need.

$result = pg_query($pg_conn, "SELECT relname FROM pg_stat_user_tables WHERE schemaname='public'");

Few examples on how to use postgresql can be found here in Official Docs

Full code I used for this answer can be found here

Leave a comment