Problem when creating a connection between PHP and Postgresql

Asked

Viewed 233 times

0

I am unable to make the connection to the Postgresql database. Follows 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;
        }
    }
}

?>
  • Set "connect right", please. Gave something error?

1 answer

1

To instantiate a PDO object you must do the following (the parameter after the password is the connection options http://php.net/manual/en/class.pdo.php)

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 excerpt

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.