最近我使用MySQL時,發(fā)現(xiàn)一個很奇怪的問題:讀取的字段值中文變成了問號。
首先我檢查了數(shù)據(jù)庫編碼,確認其為utf8mb4。
mysql>show variables like '%char%'; +--------------------------+----------------------------------------------------+ | Variable_name | Value | +--------------------------+----------------------------------------------------+ | character_set_client | utf8mb4 | | character_set_connection | utf8mb4 | | character_set_database | utf8mb4 | | character_set_filesystem | binary | | character_set_results | utf8mb4 | | character_set_server | utf8mb4 | | character_set_system | utf8 | | character_sets_dir | /usr/local/mysql5.7/share/mysql/charsets/ | +--------------------------+----------------------------------------------------+
然后我檢查了表和字段的編碼,也都為utf8mb4:
mysql>show create table accounts; CREATE TABLE `accounts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
mysql>show full columns from accounts; +-------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+ | Field | Type | Collation | Null | Key | Default | Extra | Privileges | Comment | +-------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+ | id | int(11) | NULL | NO | PRI | NULL | auto_increment | select,insert,update,references | | | name | varchar(50) | utf8mb4_general_ci | YES | | NULL | | select,insert,update,references | | +-------+--------------+--------------------+------+-----+---------+----------------+---------------------------------+---------+
最終,我發(fā)現(xiàn)問題出在了連接數(shù)據(jù)庫時沒有指定編碼:
$conn = new mysqli($servername, $username, $password, $dbname); $conn->set_charset("utf8mb4");
修改后,問題解決了。