【问题标题】:Locale of PDOException messagePDOException 消息的语言环境
【发布时间】:2013-11-10 16:44:22
【问题描述】:

这是我的代码:

$db = new PDO('mysql:host=192.168.1.1;dbname=mydb');

是否可以更改异常消息“无法连接到 '192.168.1.1' 上的 MySQL 服务器”的语言? 我用 setlocale(LC_ALL, 'ru_RU.utf8') 更改 php 语言环境,它会影响日期
不过消息是英文的。

【问题讨论】:

  • 可能值得用 MySQL 或 php 或两者标记它

标签: php mysql exception locale


【解决方案1】:
class Cp1251ErrorExeption extends ErrorException {
    public function getUtfMessage() {
        return iconv('cp1251', 'utf-8', $this->getMessage());
    }   
    function handleError($errno, $errstr, $errfile, $errline, array $errcontext){
        if (0 === error_reporting())
            return false;
    throw new self($errstr, 0, $errno, $errfile, $errline);
    }
}

try {
    try {
        set_error_handler('Cp1251ErrorExeption::handleError');  
        $db = new PDO('mysql:host=192.168.1.1;dbname=mydb');    
    } catch (PDOException $e) {
        throw new Cp1251ErrorExeption($e->getMessage());
    }   
} catch (Cp1251ErrorExeption $e) {
    echo $e->getUtfMessage();   
} 
restore_error_handler();

【讨论】:

    【解决方案2】:

    Exception 的消息是从 mysql 中 1:1 获取的。使用选项 language=russian 启动 mysqld。通常你可以在 /etc/mysql/my.cnf 的 [mysqld] 部分中配置它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      相关资源
      最近更新 更多