When developing websites or applications, using PHP and MySQL for data interaction is very common. However, sometimes we encounter garbled text, where content stored in the MySQL database is displayed incorrectly on the PHP page. Garbled text is often caused by inconsistent character encoding, improper character set settings for the database and page, or incorrect encoding during data transfer.
The following are common causes of garbled text issues:
First, ensure that the MySQL database character set is correctly configured. Use the following SQL query to check the current database character set:
SHOW VARIABLES LIKE 'character_set_database';
If the character set is not UTF-8, you can modify the database character set using the following command:
ALTER DATABASE database_name CHARACTER SET utf8 COLLATE utf8_general_ci;
In PHP, when connecting to the database, ensure that the correct character set is set to handle characters properly. The following code sets the connection character set:
$connection = new mysqli("localhost", "username", "password", "database");
In the PHP page, ensure that the character set matches the one used by the database. Add the following code inside the tag on the page:
<meta charset="utf-8">
When performing database operations, ensure that the data encoding is consistent. Use PHP's mb_convert_encoding function to convert encoding:
$str = mb_convert_encoding($str, "UTF-8", "GB2312");
Suppose we have a table named example_table that stores Chinese content. The following PHP code queries and outputs the content from the table:
$connection = new mysqli("localhost", "username", "password", "database");
Using the above code, we can correctly query and display Chinese content from the database, avoiding garbled text.
In PHP and MySQL development, garbled text is a common challenge. By correctly configuring the database character set, database connection character set, page character set, and performing necessary encoding conversions, we can effectively solve garbled text issues. Additionally, following these solutions ensures that data is displayed correctly on the page and improves user experience.
Related Tags:
MySQL