PHP使用PDO操作数据库的乱码问题解决方法,pdo乱码
本文实例讲述了PHP使用PDO操作数据库的乱码问题解决方法。分享给大家供大家参考,具体如下:
当使用 PDO 连接操作数据库的时候,有时会出现:保存在数据库中的汉字为乱码。以文件为 UTF-8 格式,其解决方法如下:
(1)实例化的对象直接执行 query() 方法或者 exec() 方法:
<?php class DB { static public function getDB() { try { $_opts_values = array(PDO::ATTR_PERSISTENT=>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; } } ?>
(2)在实例化 PDO 的第四个参数添加 MYSQL_ATTR_INIT_COMMAND 属性:
<?php class DB { static public function getDB() { try { $_opts_values = array(PDO::ATTR_PERSISTENT=>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; } } ?>
注:以上方法,都经过测试。
更多关于PHP相关内容感兴趣的读者可查看本站专题:《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。
您可能感兴趣的文章:
- 在PHP中PDO解决中文乱码问题的一些补充
- php PDO中文乱码解决办法
- PHP中PDO的事务处理分析
- PHP的PDO常用类库实例分析
- PHP的PDO操作简单示例
- PHP5.2中PDO的简单使用方法
- php中PDO方式实现数据库的增删改查
- php中mysql连接方式PDO使用详解
- php中数据库连接方式pdo和mysqli对比分析
- PHP PDO fetch 模式各种参数的输出结果一览
- php使用PDO方法详解

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function