This article is an example of the use of PHP PDO operation database garbled problem solving method. Share to everyone for your reference, specific as follows:
When using the PDO connection to manipulate the database, it sometimes appears: the Chinese characters in the database are garbled. In a file-UTF-8 format, the solution is as follows:
(1) The instantiated object executes the query () method directly or the Exec () method:
<?php
class DB {
static public function Getdb () {
try {
$_opts_values = array (pdo::attr_persistent=& GT;TRUE,PDO::ATTR_ERRMODE=>2);
$_pdo = new PDO (DB_DSN, Db_name, Db_pass, $_opts_values);
catch (Pdoexception $e) {
exit (' Database connection Error! Error message: '. $e->getmessage ());
}
$_pdo->query ("SET NAMES UTF8"); $_pdo->exec (' SET NAMES utf8 '); Set the database encoding, both methods can return
$_pdo
}
? >
(2) Add the Mysql_attr_init_command property to the fourth parameter of the instantiated PDO:
<?php
class DB {
static public function Getdb () {
try {
$_opts_values = array (pdo::attr_persistent=& Gt;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 (' Database connection Error! Error message: '. $e->getmessage ());
}
return $_pdo;
}
? >
Note: The above methods have been tested.
More about PHP Interested readers can view the site topics: "PHP based on PDO Operation Database Skills summary", "PHP operation and operator Usage Summary", "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", "PHP operation Office Document Skills Summary ( including word,excel,access,ppt), the "Summary of PHP date and time usage", "PHP Introduction to Object-oriented Programming", "PHP string (String) Usage Summary", "Php+mysql database Operation Tutorial" and " A summary of common PHP database operations tips
I hope this article will help you with the PHP program design.