9

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") );

}
hjpotter92
  • 75,209
  • 33
  • 136
  • 171
vili
  • 317
  • 3
  • 6
  • 13
  • 1
    For what it's worth, it appears to default to UTF-8 for me without explicitly setting it on a default Postgres installation. I can't find a documented switch for this either though ATM. – deceze Aug 15 '13 at 09:52
  • Why do you need all these private variables? $user, $db, $pass? – Your Common Sense Aug 15 '13 at 09:56
  • It's need because, mysql database didn't work with cyrillic symbols, before this command. – vili Aug 15 '13 at 09:59
  • This private variable need because I use object oriented way and I change the databases from MySQL to PgSQL – vili Aug 15 '13 at 10:01

3 Answers3

5

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...

Henry Ruhs
  • 1,193
  • 1
  • 14
  • 25
3

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';
Richard Huxton
  • 19,615
  • 3
  • 35
  • 46
hjpotter92
  • 75,209
  • 33
  • 136
  • 171
1

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
Your Common Sense
  • 154,967
  • 38
  • 205
  • 325
  • 5
    Strange thing is for pgsql it is *not* in the manual for the dsn. docsbug? – PeeHaa Aug 15 '13 at 09:57
  • I try this: `$this->conn = new PDO("pgsql:host=".$this->host.";dbname=".$this->db,$this->user,$this->pass,$this->SET CLIENT_ENCODING TO 'UTF8');`, but I have mistake: syntax error, unexpected T_STRING – vili Aug 15 '13 at 10:15
  • 3
    @vili you have to have basic understanding of PHP syntax first. – Your Common Sense Aug 15 '13 at 11:21
  • 5
    Ad DSN charset, I've got error `invalid connection option "charset"`. Should be `'options=\'--client_encoding' . $params['charset']` see http://www.doctrine-project.org/jira/browse/DBAL-567 – xmedeko May 14 '14 at 12:07