2

I have this block of PHP code that is supposed to connect to a PostgreSQL database in heroku

Code Below:

function __construct() {

            $host = 'hostname';
            $user = 'username';
            $password = 'password';
            $dbname = 'db_name';
            $port = '5432';

            try{
                $this->db = new PDO('pgsql:host=$host;dbname=$dbname;user=$user;port=$port;password=$password');


            }
            catch (PDOException $e){
                echo 'Connection failed: ' . $e->getMessage();
            }


        }

The connection throws an arror as follows:

Connection failed: SQLSTATE[08006] [7] invalid port number: "$port"

Why do I get an invalid port number?

Everything seems okay when I connect via the heroku cli but the php doesn't seem to cooperate.

Please help me figure out what I may have overlooked.

Selase
  • 175
  • 5
  • 24

1 Answers1

0

Variables are only expanded in double quoted strings.

$this->db = new PDO("pgsql:host=$host;dbname=$dbname;user=$user;port=$port;password=$password");

It probably complains about $port specifically because it is trying to convert that one to an int before trying to make the connection. If it would have gotten that far it would also have complained about the hostname.

Eelke
  • 20,897
  • 4
  • 50
  • 76