Problem creating a connection between PHP and PostgreSQl [closed]

0

I am not able to connect to the PostgreSQL database. Here is the code:

<?php

class Conexao {
    private $usuario;
    private $senha;
    private $banco;
    private $servidor; 
    private $porta;
    private static $pdo;
    //Método construtor conexao
    public function __construct() {
        $this->servidor = "localhost";
        $this->banco = "emporio";
        $this->usuario = "postgres";
        $this->senha = "gui1234"; 
        $this->porta = "5432";
    }
    //Método para conexão
    public function conectar(){
        try {
            //verificando se atributo pdo está estanciado
            if (is_null(self::$pdo)) {
                //Estanciando conexao
                self::$pdo = new PDO("pgsql:host=".$this->servidor.";dbname=".$this->banco, $this->usuario, $this->senha,$this->porta);

            }
            return self::$pdo;// se já estiver estanciado, retorna.

        } catch (PDOException $ex) {
            echo "erro".ex->getMessage;
        }
    }
}

?>
    
asked by anonymous 19.12.2018 / 14:32

1 answer

1

To instantiate a PDO object you must do the following (the parameter after the password is the connection options link

self::$pdo = new PDO("pgsql:host=".$this->servidor.";port=".$this->porta.";dbname=".$this->banco, $this->usuario, $this->senha);

If you want to use the configuration option you can do so

$options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
self::$pdo = new PDO("pgsql:host=".$this->servidor.";port=".$this->porta.";dbname=".$this->banco, $this->usuario, $this->senha,$options);

Another thing I saw that needs adjustment is the stretch

catch (PDOException $ex) {
        echo "erro".ex->getMessage; // É echo "erro". $ex->getMessage();
    }
    
19.12.2018 / 20:20