【问题标题】:PHP PDO ,Can't set name while connection is persistant?PHP PDO,连接持久时无法设置名称?
【发布时间】:2015-12-26 02:49:28
【问题描述】:

这是我的 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();
    }
}

之间是否有冲突:

PDO::MYSQL_ATTR_INIT_COMMAND =>  'SET NAMES utf8'

还有:

PDO::ATTR_PERSISTENT => true

【问题讨论】:

  • 文件的编码类型是什么?
  • 奇怪的是,它是asked before,几乎没有引起注意。
  • 您是否尝试将charset 直接设置到连接字符串中?喜欢dbname=' . $this->dbname;charset=utf8
  • Found one,看看有没有帮助。

标签: php database pdo utf-8 character-encoding


【解决方案1】:

我可以找到答案here

在 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();
        }
    }

现在输出是正确的。

【讨论】:

  • 很高兴看到它有帮助:)
猜你喜欢
  • 1970-01-01
  • 2018-10-19
  • 1970-01-01
  • 2011-05-20
  • 2013-10-24
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2015-05-19
相关资源
最近更新 更多