PDO鏈接mysql8.0報PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to

安裝mysql8.0以後,嘗試使用php鏈接mysql,老是報PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers錯誤,網上找了不少資料,然而都沒有多大用處。php

查找了mysql官方說明文檔才知道原來M8.0已經已經把默認字符集升級成ut8mb4了,因而找到my.cnf文件,修改以下:html

 1 [client]
  2 port = 3306
  3 socket = /tmp/mysql.sock
  4 default-character-set = utf8 5 
  6 [mysql]
  7 prompt="MySQL [\d]> "
  8 no-auto-rehash
  9 default-character-set = utf8 10 
 11 [mysqld]
 12 port = 3306
 13 socket = /tmp/mysql.sock
 14 default_authentication_plugin = mysql_native_password
 15 collation-server = utf8_unicode_ci 16 
 17 basedir = /usr/local/mysql
 18 datadir = /data/mysql
 19 pid-file = /data/mysql/mysql.pid
 20 user = mysql
 21 bind-address = 0.0.0.0
 22 server-id = 1
 23 
 24 init-connect = 'SET NAMES utf8'
 25 character-set-server = utf8

 而後使用PDO鏈接mysqlmysql

$db = array(  
    'host' => 'your host',         //設置服務器地址  
    'port' => '3306',              //設端口   
    'dbname' => 'your db name',    //設置數據庫名        
    'username' => 'your name',     //設置帳號  
    'password' => 'your pwd',      //設置密碼  
    'charset' => 'utf8',           //設置編碼格式  
    'dsn' => 'mysql:host=your host;dbname=your db name;port=3306;charset=utf8',   
);  
  
//鏈接  
$options = array(  
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,     //默認是PDO::ERRMODE_SILENT, 0, (忽略錯誤模式)  
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,   // 默認是PDO::FETCH_BOTH, 4  
);  
  
try{  
    $pdo = new PDO($db['dsn'], $db['username'], $db['password'], $options);
    var_dump($pdo);  
}catch(PDOException $e){  
    die('數據庫鏈接失敗:' . $e->getMessage());  
}

結果以下:sql

object(PDO)#1 (0) { }數據庫

相關文章
相關標籤/搜索