Fix PHP Database Garbled Characters
The issue of garbled characters when reading databases in PHP is usually caused by a mismatch between the character sets of the database and the PHP code. Here are some solutions:
- Check the character set of the database and tables: Make sure the character set of the database and tables is set correctly, common character sets include UTF-8, GBK, etc. You can confirm by checking the character set in the database.
- Set the character encoding for PHP code: Use the mysqli_set_charset() function in PHP code to ensure it matches the character encoding of the database.
// 设置字符集为UTF-8
mysqli_set_charset($conn, 'utf8');
- establish a connection with MySQL database
// 连接数据库并设置字符集为UTF-8
$conn = mysqli_connect($host, $username, $password, $database);
mysqli_set_charset($conn, 'utf8');
- Change the structure of the table
ALTER TABLE table_name CONVERT TO CHARACTER SET utf8;
- Convert the encoding using mb_convert_encoding().
$data = mb_convert_encoding($data, 'UTF-8', '原字符集');
- HTML element to provide metadata about the webpage.
<meta charset="UTF-8">
By implementing the above methods, the issue of PHP reading database gibberish can be resolved. Choose the appropriate method based on the specific situation.