exec('SET NAMES utf8');"; 2. Add the "MYSQL_ATTR_INIT_COMMAND" attribute to the fourth parameter of instantiated PDO."> How to set encoding in php pdo-PHP Problem-php.cn

How to set encoding in php pdo

藏色散人
Release: 2023-03-09 21:32:01
Original
2864 people have browsed it

php pdo setting encoding method: 1. Set the database encoding through "$_pdo->exec('SET NAMES utf8');"; 2. Add "MYSQL_ATTR_INIT_COMMAND" to the fourth parameter of instantiated PDO "Attributes.

How to set encoding in php pdo

The operating environment of this article: windows7 system, php5.2.4 version, DELL G3 computer

Solution to the garbled problem of PHP using PDO to operate the database, php pdo setting encoding:

When using PDO connection to operate the database, sometimes it will appear: the Chinese characters saved in the database are garbled. If the file is in UTF-8 format, the solution is as follows:

(1) The instantiated object directly executes the query() method or exec() method:

true,PDO::ATTR_ERRMODE=>2); $_pdo = new PDO(DB_DSN, DB_NAME, DB_PASS, $_opts_values); } catch (PDOException $e) { exit('数据库连接错误!错误信息:'.$e->getMessage()); } $_pdo->query("SET NAMES utf8"); // $_pdo->exec('SET NAMES utf8'); //设置数据库编码,两种方法都可以 return $_pdo; } } ?>
Copy after login

(2) In the instance Add the MYSQL_ATTR_INIT_COMMAND attribute to the fourth parameter of PDO:

true,PDO::ATTR_ERRMODE=>2,PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES utf8'); $_pdo = new PDO(DB_DSN, DB_NAME, DB_PASS, $_opts_values); } catch (PDOException $e) { exit('数据库连接错误!错误信息:'.$e->getMessage()); } return $_pdo; } } ?>
Copy after login

Note: The above methods have been tested.

[Recommended learning:PHP video tutorial]

The above is the detailed content of How to set encoding in php pdo. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!