Home >Backend Development >PHP Problem >How to set the database connection encoding format in PHP
PHP is a commonly used server-side programming language that is often used in conjunction with databases. During the process of writing code, it is necessary to set and connect the corresponding encoding format to ensure the correct display and reading and writing operations of special characters such as Chinese.
1. PHP encoding settings
1. Set the default character set
PHP uses the header() function to set HTTP header information, including character set settings. Using utf-8 encoding can support Chinese and other language characters. The code is as follows:
header("Content-type: text/html; charset=utf-8");
2. Encode the string
Use the mb_internal_encoding() function to change the PHP default character set to utf -8 to ensure the correct encoding of the string:
mb_internal_encoding("UTF-8");
3. Encoding the input and output streams
In read and write operations with files or other sources, you can use the fopen() function The mode parameter opens a file or stream and specifies the encoding format. For example:
$fp = fopen("$filename", "r") or die("文件打开失败!"); stream_filter_append($fp, 'convert.iconv.UTF-8/GBK');
2. Database encoding settings and connection
1. Database encoding settings
In the MySQL database, you can view the default character set through the following command:
mysql> SHOW VARIABLES LIKE 'character_set%';
If you need to change the character set, you can use the SET NAMES command, for example:
mysql> SET NAMES 'utf8';
2. Database connection settings
In PHP, the connection to MySQL is through mysqli () and PDO() are implemented by two classes. The connection example using mysqli() is as follows:
$conn = mysqli_connect($server, $user, $password, $dbname); mysqli_set_charset($conn, 'utf8');
The connection example using PDO() is as follows:
$dsn = "mysql:host=$host;dbname=$dbname;charset=utf8mb4"; $options = [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false, ]; $pdo = new PDO($dsn, $user, $password, $options);
The above is an introduction to the encoding format of PHP settings, databases and their connections. In actual programming, appropriate methods need to be selected for setting and connection based on specific circumstances to ensure the correctness and stability of the code when processing special characters such as Chinese.
The above is the detailed content of How to set the database connection encoding format in PHP. For more information, please follow other related articles on the PHP Chinese website!