PDO连接mysql8.0报PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers错误
时间:2022-03-15 08:49
安装mysql8.0之后,尝试使用php连接mysql,总是报错误,网上找了很多资料,然而都没有多大用处。
查找了mysql官方说明文档才知道原来M8.0已经已经把默认字符集升级成ut8mb4了,于是找到my.cnf文件,修改如下:
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连接mysql
$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()); }
结果如下:
object(PDO)#1 (0) { }