5

This is a part of my PDO class. I need to use utf-8 for Hebrew language but when i set ATTR_PERSISTENT to true the output text will be shown like ?????? If I switch the ATTR_PERSISTENT to false the output will be right.

public function __construct() {
    // Set DSN
    $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
    // Set options
    $options = array(
        PDO::MYSQL_ATTR_INIT_COMMAND =>  'SET NAMES utf8',
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_PERSISTENT => true
    );
    // Create a new PDO instanace
    try {
        $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
    }
    // Catch any errors
    catch (PDOException $e) {
        $this->error = $e->getMessage();
    }
}

Is there any conflict between:

PDO::MYSQL_ATTR_INIT_COMMAND =>  'SET NAMES utf8'

And:

PDO::ATTR_PERSISTENT => true
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
Amin Gholibeigian
  • 1,325
  • 2
  • 9
  • 11
  • What are the encode type of file? – rray Sep 28 '15 at 19:32
  • What is curious, is that it was [asked before](http://stackoverflow.com/questions/29714253/pdoattr-persistent-utf-8-encoding) and caught almost no attention. – al'ein Sep 28 '15 at 19:33
  • 1
    Did you try setting the `charset` directly into the connection string? Like `dbname=' . $this->dbname;charset=utf8`? – al'ein Sep 28 '15 at 19:38
  • [Found one](http://stackoverflow.com/questions/4475548/pdo-mysql-and-broken-utf-8-encoding), see if it helps. – al'ein Sep 28 '15 at 19:42

1 Answers1

2

I could find the answer here .

Setting it in DSN is the only proper way, so i changed the code to this :

 public function __construct() {
        // Set DSN
        $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname .';charset=utf8';
        // Set options
        $options = array(
            //PDO::MYSQL_ATTR_INIT_COMMAND =>  "SET NAMES utf8",
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_PERSISTENT => true
        );
        // Create a new PDO instanace
        try {
            $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
        }
        // Catch any errors
        catch (PDOException $e) {
            $this->error = $e->getMessage();
        }
    }

And now the output is right.

Community
  • 1
  • 1
Amin Gholibeigian
  • 1,325
  • 2
  • 9
  • 11