PHP PDO,连接持久时无法设置名称?

时间:2022-09-22 16:12:20

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.

这是我的PDO课程的一部分。我需要使用utf-8作为希伯来语,但是当我将ATTR_PERSISTENT设置为true时,输出文本将显示为??????如果我将ATTR_PERSISTENT切换为false,则输出将是正确的。

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

1 个解决方案

#1


2  

I could find the answer here .

我可以在这里找到答案。

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

在DSN中设置它是唯一正确的方法,所以我将代码更改为:

 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.

现在输出是正确的。

#1


2  

I could find the answer here .

我可以在这里找到答案。

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

在DSN中设置它是唯一正确的方法,所以我将代码更改为:

 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.

现在输出是正确的。