php访问MySQL 8.0 utf8mb4报错的解决方案

阅读 33

2023-11-26

由于MySQL 8.0默认字符集是 utf8mb4,PHP访问会报错,报错信息如下所示:

PHP Warning:  mysqli_connect(): Server sent charset (255) unknown to the client. Please, report to the dev

elopers in /root/php_utf8mb4/conn.php on line 4PHP Warning:  mysqli_connect(): (HY000/2054): Server sent charset unknown to the client. Please, report to

the developers in /root/php_utf8mb4/conn.php on line 4数据库链接错误

Server sent charset unknown to the client. Please, report to the developers

解决方案

在/etc/my.cnf配置文件添加如下

character-set-server = utf8mb4

collation-server = utf8mb4_unicode_ci

见红色的参数,并重启mysqld进程生效。

之后,再通过php连接一切正常。

测试代码:

<?php  
 
try {
    $con = mysqli_connect("192.168.198.239", "admin", "hechunyang", "test", "3346") or die("数据库链接错误
\n" . mysqli_connect_error()."\n");
    mysqli_query($con, "set names utf8");
    
    // 在这里添加你的数据库操作代码
    
} catch (Exception $e) {
    echo "发生异常:" . $e->getMessage();
}  
    
?>

感谢研发工程师@豆豆老爹的技术支持。

精彩评论(0)

0 0 举报