How to solve the problem of garbled code when connecting PHP to MySQL
MySQL is a commonly used relational database management system, and PHP is a popular server-side scripting language. The two are often used together to develop websites and applications. When using PHP to connect to a MySQL database, we often encounter the problem of garbled Chinese data, which brings some trouble to developers. This article will introduce some effective methods to solve the garbled problem of PHP connection to MySQL, and provide specific code examples.
First make sure that the character set settings of the database and table are correct. When creating the database, you should choose an appropriate character set, such as utf8 or utf8mb4. Also specify the correct character set and collation rules when creating the table. 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 PHP connects to the MySQL database, you need to set the character set to utf8mb4 to ensure the correct storage and reading of data. . You can add the following statement in the code to connect to the database:
$mysqli = new mysqli("localhost", "username", "password", "my_database"); $mysqli->set_charset("utf8mb4");
Before executing the SQL query statement, you also need to set the character set to utf8mb4 . You can add the following statement before executing the query statement:
$mysqli->query("SET NAMES 'utf8mb4'");
When processing Chinese data in PHP, you need to ensure that you use UTF- 8 encoding. UTF-8 encoding is used when saving data to or reading data from the database. For example:
$name = "张三"; $name = utf8_encode($name); // 将字符串转换为 UTF-8 编码 $result = $mysqli->query("INSERT INTO my_table (name) VALUES ('$name')");
Finally, when displaying data on a web page, you must also set the page encoding to UTF-8 to ensure Chinese The data is displayed correctly. You can add the following code to the HTML header:
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
Through the above method, you can effectively solve the Chinese data garbled problem that occurs when PHP connects to the MySQL database. Following the correct character set settings and encoding specifications can ensure the correct storage, reading and display of data. I hope the above content is helpful to everyone.
The above is the detailed content of An effective way to solve the problem of garbled code when connecting PHP to MySQL. For more information, please follow other related articles on the PHP Chinese website!