Home > Article > Backend Development > Garbled characters occur when php inserts data into the database
The solution to garbled data when php inserts data into the database: first set the encoding of the database to utf8; then determine the text encoding method to be inserted into the database; finally, use the switch statement to determine the data insertion.
Recommended: "PHP Video Tutorial"
php inserts data into the database and the problem of garbled characters occurs
Generally, the garbled data inserted into the database is an encoding problem. You can check the encoding method of the content before inserting into the database. If it is the same as the encoding method used by the database (such as: utf-8), perform the insertion. If the operation is different, transcode it.
First determine the encoding method of the text you want to insert into the database. If it is utf-8, insert it. If not, convert it to utf-8 and then insert it:
$e=mb_detect_encoding($text, array('UTF-8', 'GBK', 'gb2312')); switch($e){ case 'UTF-8' : //如果是utf8编码就直接插入数据库 break; case 'GBK': //如果是gbk编码就转换为utf-8之后再插入数据库 iconv("GBK", "UTF-8",$data) ; break; case 'GB2312': //如果是GB2312编码就转换为utf-8之后再插入数据库 iconv("GB2312", "UTF-8",$data) ; break; }
I thought the encoding in the program If it is consistent with the encoding used in the database, there will be no garbled characters. However, the data inserted into the database still has garbled characters. After ruling out the inconsistency in encoding, I thought that it might be because the mysql encoding was not set when using PHP to connect to mysql. Sure enough, After connecting to the database, set the encoding of the database to utf8 and then insert the database into the database without garbled characters.
The code is as follows:
$this->conn = mysqli_connect($db['default']['hostname'], $db['default']['username'], $db['default']['password'], $db['default']['dbname']) or die('Connect error!'); //连接到数据库 mysqli_set_charset($this->conn, 'utf8'); //此处不能用utf-8
The above is the detailed content of Garbled characters occur when php inserts data into the database. For more information, please follow other related articles on the PHP Chinese website!