MySQL is a widely used relational database management system, and PHP is a popular server-side scripting language. They are often used together in website and application development. During development, developers often encounter issues with Chinese character encoding when PHP connects to MySQL. This article introduces effective solutions to help developers resolve character encoding issues between PHP and MySQL.
First, make sure that the character set for the database and table is correctly set. When creating the database, choose a suitable character set like UTF-8 or UTF-8MB4. The character set and collation for the table should also be set to UTF-8MB4 to ensure proper data storage. For example:
CREATE DATABASE my_database CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE TABLE my_table (id INT AUTO_INCREMENT, name VARCHAR(50) CHARACTER SET utf8mb4, PRIMARY KEY(id)) ENGINE=InnoDB CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
When connecting to the MySQL database with PHP, explicitly set the character set to utf8mb4 to ensure correct data storage and retrieval. The following code example demonstrates this:
$mysqli = new mysqli("localhost", "username", "password", "my_database");
$mysqli->set_charset("utf8mb4");
Before executing SQL queries, ensure that the character set is set to utf8mb4. This can prevent Chinese data from being garbled. Here's an example of how to set the character set before running a query:
$mysqli->query("SET NAMES 'utf8mb4'");
When handling Chinese data in PHP, ensure that UTF-8 encoding is used. When inserting data into the database or retrieving it, always make sure it’s in UTF-8. For example:
$name = "张三";
$name = utf8_encode($name); // Convert to UTF-8 encoding
$result = $mysqli->query("INSERT INTO my_table (name) VALUES ('$name')");
Finally, when displaying data on a webpage, ensure that the page’s encoding is set to UTF-8 so that Chinese characters display correctly. Add the following code in the HTML head section:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
By following these methods, developers can effectively resolve Chinese character encoding issues when PHP connects to MySQL. Proper character set settings and encoding standards will ensure correct data storage, retrieval, and display. We hope these tips help developers in their work.