Home >Backend Development >PHP Tutorial >How to deal with garbled characters when PHP is stored in the database
How to deal with garbled characters when PHP is stored in the database
In the development process, we often encounter problems when saving data to the database Garbled characters. This situation is usually caused by the encoding of the data being inconsistent with the encoding of the database. Especially when using PHP to operate a MySQL database, special attention needs to be paid to dealing with garbled characters. This article will introduce several common processing methods and give specific code examples.
1. Set the database encoding
Before connecting to the database, you should first set the encoding of the database to ensure that the encoding of the database is consistent with the encoding of the application. Generally speaking, commonly used encoding methods include UTF-8, GBK, etc. The following is a code example for setting the database encoding:
$servername = "localhost"; $username = "username"; $password = "password"; $dbname = "dbname"; $conn = new mysqli($servername, $username, $password, $dbname); $conn->set_charset("utf8"); // 设置数据库编码为UTF-8
2. Setting the PHP encoding
Before storing data into the database, you should ensure that the encoding of the PHP script is also consistent with the database encoding. The encoding can be set in the PHP script, for example:
header('Content-Type: text/html; charset=utf-8'); mb_internal_encoding('UTF-8');
3. Processing data encoding
Sometimes the data obtained from the form may be presented in other encodings and needs to be converted into a database Supported encoding forms. You can use PHP's built-in mb_convert_encoding
function to perform encoding conversion, for example:
$data = $_POST['data']; $data = mb_convert_encoding($data, 'UTF-8', 'GB2312');
4. Use prepared statements
Prepared statements are a safe way to insert into the database data, it will automatically handle data encoding issues to avoid garbled characters. The following is a sample code that uses prepared statements to insert data into the database:
$stmt = $conn->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)"); $stmt->bind_param("ss", $data1, $data2); $data1 = "数据1"; $data2 = "数据2"; $stmt->execute();
The above are some common methods and code examples for dealing with garbled characters when PHP is stored in the database. By properly setting database encoding, PHP encoding, data encoding, and using preprocessing statements, you can effectively avoid data garbled problems.
The above is the detailed content of How to deal with garbled characters when PHP is stored in the database. For more information, please follow other related articles on the PHP Chinese website!