PHP is a powerful server-side scripting language that is widely used in the field of web development. When using PHP for database operations, you sometimes encounter the problem of garbled characters stored in the database, especially when Chinese data is involved. This article will introduce how to solve the problem of garbled characters stored in PHP databases, and attach specific code examples.
First, make sure the character set of the database table is set to UTF-8, so as to ensure that the database can correctly store Chinese characters. You can set the character set of the database and table through the following SQL statement:
ALTER DATABASE your_database_name CHARACTER SET utf8 COLLATE utf8_unicode_ci; ALTER TABLE your_table_name CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
When PHP connects to the database, you need to set the connection character set to UTF -8 to ensure the data is transferred to the database correctly. You can set the character set when PHP connects to the database through the following code example:
$host = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_database_name"; $conn = new mysqli($host, $username, $password, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // 设置连接字符集为UTF-8 $conn->set_charset("utf8");
Before executing the SQL statement, you need to set the character set for PHP to send SQL statements. The character set is UTF-8 to ensure correct transmission of Chinese data. You can use the following code example to set the character set for PHP to send SQL statements:
// 设置发送SQL语句的字符集为UTF-8 mysqli_query($conn, "SET NAMES utf8"); // 执行SQL语句 $sql = "INSERT INTO your_table_name (column_name) VALUES ('中文数据')"; $result = mysqli_query($conn, $sql); if ($result) { echo "数据插入成功"; } else { echo "数据插入失败: " . mysqli_error($conn); }
Through the above method, you can effectively solve the problem of garbled characters stored in the PHP database and ensure that Chinese data can be correctly stored in the database. Hope the above content is helpful to you.
The above is the detailed content of Solution to the problem of garbled storage in PHP database. For more information, please follow other related articles on the PHP Chinese website!