Garbled characters occur when php inserts data into the database

藏色散人
Release: 2023-03-06 09:46:01
Original
2953 people have browsed it

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.

Garbled characters occur when php inserts data into the database

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;
        }
Copy after login

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
Copy after login

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!

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template