0

I'm looking for a way to connect to the postgresql database using UTF8 charset.

Currently, I have to send a query request after the connexion to specify the charset. It is not optimal at all...

    $connect = new \PDO("pgsql:host=$this->host;dbname=$this->base", $this->user, $this->pass);
    $connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
    $connect->query("SET NAMES '$this->charset'");

MySQL allows to pass a table on argument to specify the charset, I'm looking for the same thing.

        $this->db = new \PDO("pgsql:host=$this->PARAM_hote;dbname=$this->PARAM_nom_bd", $this->PARAM_utilisateur, $this->PARAM_mot_passe, array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''));
        $this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
Macbernie
  • 1,303
  • 6
  • 24
  • 48
  • Have you tried using `charset=CHARSET_HERE` in the connection string? Something like `...dbname=SOME_DB;charset=SOME_CHARSET...` – FirstOne Jul 19 '16 at 00:24
  • For reference: [How to support UTF-8 completely in a web application](http://stackoverflow.com/questions/279170/how-to-support-utf-8-completely-in-a-web-application) – FirstOne Jul 19 '16 at 00:25

3 Answers3

4

Went with :

new PDO('pgsql:host=' .  $db_host . ';dbname=' . $db_name . ';options=\'--client_encoding=UTF8\'', $db_username, $db_password, array(PDO::ATTR_PERSISTENT => true));

As a matter of fact, the single quote to pass the option --client_encoding=UTF8 is very important and a double one doesn't works.

Apex
  • 393
  • 1
  • 6
  • 17
2

You can pass 'options' key like this:

$dbh = new PDO
  (
    "pgsql:dbname=mydbname;host=myhost;port=5432;options='--client_encoding=UTF8'",
    "username",
    "password"
   );
-1

Try add params in constructor:

$connect = new \PDO("pgsql:host=$this->host;dbname=" . $this->base . ";options='-c client_encoding=utf8'", $this->user, $this->pass);
$connect->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
vitaliytv
  • 694
  • 7
  • 9