How set UTF-8 in PDO class constructor for PHP PgSQL database

18,011

Solution 1

From what I see in section 21.2.3 on this page, you can use one of the following two commands:

  1. SET CLIENT_ENCODING TO 'value';
  2. SET NAMES 'value';

where value = UTF8. Try using:

SET CLIENT_ENCODING TO 'UTF8';

or

SET NAMES 'UTF8';

Solution 2

Let me point out the comment by xmedeko, that is absolute right:

pg_connect("host=localhost options='--client_encoding=UTF8'");

Source: http://php.net/manual/en/function.pg-connect.php

Using charset=utf8 is working (only) with mysql...

Solution 3

it is very easy to find an analog for the regular SQL query

$pdo->query("SET NAMES UTF8")

However, encoding have to be set in DSN anyway

$this->conn = new PDO("pgsql:host=".$this->host.";dbname=".$this->db.";charset=".$this->charset
Share:
18,011
vili
Author by

vili

Updated on July 25, 2022

Comments

  • vili
    vili almost 2 years

    I want to set UTF8 for my PDO object. This class works correctly with MySQL. I can't find an analog of array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8") for PgSQL and I can't work with cyrillic symbols.

    class oop{
    private $host="localhost";
        private $user="xxxx";
        private $db="xxxx";
        private $pass="111111";
        private $conn;
    
    public function __construct(){
    
        $this->conn = new PDO("pgsql:host=".$this->host.";dbname=".$this->db,$this->user,$this->pass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES UTF8") );
    
    }
    
  • PeeHaa
    PeeHaa over 10 years
    Strange thing is for pgsql it is not in the manual for the dsn. docsbug?
  • vili
    vili over 10 years
    I try this: $this->conn = new PDO("pgsql:host=".$this->host.";dbname=".$this->db,$this->us‌​er,$this->pass,$this‌​->SET CLIENT_ENCODING TO 'UTF8');, but I have mistake: syntax error, unexpected T_STRING
  • Your Common Sense
    Your Common Sense over 10 years
    @vili you have to have basic understanding of PHP syntax first.
  • xmedeko
    xmedeko almost 10 years
    Ad DSN charset, I've got error invalid connection option "charset". Should be 'options=\'--client_encoding' . $params['charset'] see doctrine-project.org/jira/browse/DBAL-567