# 一、php封裝pdo操作類
## 為什么使用PDO?
簡單粗暴啊,不同數據庫,只需要更改下數據庫連接方式即可,通俗來說,就是萬金油!
而且PDO更安全!
具體和其它操作數據庫的擴展的不同,可以去查詢
# 一.如何安裝PDO連接數據庫
PDO從PHP5.1開始,就攜帶了此擴展,如果你的PHP不支持,請升級到5.1或者更高版本
開啟方式:找到php.ini
如果你的php版本<5.3
你需要加入以下內容:
`extension=php_pdo.dll`
如果你的PHP版本>=5.3
你只需要在配置文件加入以下內容:
如果你操作的是其它數據庫,請選擇其它擴展
如果你的頁面存在此內容,請刪除其前面的 ; 以打開此擴展
此時,重啟你的PHP即可!
如果你使用的是本教程推薦的phpstudy,你可以更簡單的開啟pdo擴展
選擇其它選項->PHP擴展及設置->PHP擴展->如果已經打鉤說明已經開啟,否則點擊此擴展,然后點擊重啟即可
# 二.PDO如何連接數據庫
我們直接來看個例子
```
$db = new PDO("mysql:host=localhost;dbname=myblog","root","root");
var_dump($db);
$res = $db->query('select * from od_admin ');
$res = $res->fetchAll(PDO::FETCH_ASSOC);
echo "";
print_r($res);
echo "";
exit;
```
#### 注意,請自行在數據庫myblog中的admin表添加數據
我們可以看到,他輸出了三條數據,這三條數據是我剛才加入的數據
這樣,表示我們已經成功連接到數據庫,并且執行了簡單的sql語句,我們來分析下
```
$db = new PDO("mysql:host=localhost;dbname=myblog","root","root");
```
這里的localhost就是我們的數據庫地址,也可以寫作 127.0.0.1
dbname 就填寫你的數據庫名詞
最后面兩個參數是賬號 密碼,根據你實際情況填寫即可!
```
$db->query('select * from od_admin ');
```
$db,就是我們剛才實例化的PDO類的對象,query就是PDO底層給我提供的執行sql語句的方法
這句就是查詢所有admin表下的數據
```
$res = $res->fetchAll(PDO::FETCH_ASSOC);
```
這句的意思就是說將返回所有的數據以數組的方式返回,并且如果不加 FETCH\_ASSOC ,
返回的數據是字段為一個元素,值為一個元素,
# 三.封裝PDO操作類 (這才是重點)
我們開發中,并不需要每次都去連接數據庫進行操作,而且我們想使用一些便捷的查詢語句,而不是
每次都去寫sql語句怎么辦?
我們可以封裝成一個數據庫操作類,每次使用的時候實例化他即可!
①.我們先寫一個名字叫做DbDriver.php的腳本
②.我們說過,類的關鍵詞是class, 并且+類名和花括號,所以,你應該有一下代碼
```
<?php
class DbDriver
{
}
```
③.接下來我們開始分析如何去寫這個類
首先呢,連接數據庫,肯定要有數據庫地址,賬號密碼等,所以我們申明一個屬性,叫做config
```
protected $config;
```
我們連接數據庫成功,肯定還要有一個屬性去接受數據庫連接成功后返回對象
```
private $pdo;
```
接下來我們寫連接的方法
我們在寫這種工具類的時候,一般情況下,最好是實例化好這個類的時候,就可以使用了
所以,我們在構造方法里去寫數據庫連接
```
function __construct($config)
{
//判斷這個屬性是否為空,為空則去實例化,否則直接返回
if(is_null($this->pdo)){
//把傳遞過來配置文件傳遞賦給屬性
$this->config = $config;
$dsn = 'mysql:dbname=' . $this->config["DBNAME"] . ';host=' . $this->config["HOST"] . '';
try {
//設置輸出編碼為UTF8
$this->pdo = new PDO($dsn, $this->config["USER"], $this->config["PWD"], array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
//設置 ATTR_ERRMODE 的值為ERRMODE_EXCEPTION(拋出異常)
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//這是值取消 PHP本地模擬prepare,也就是會把參數和sql發送給數據庫去進行轉義處理[防注入]
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (PDOException $e) {
//這兩個方法是PDO提供的,一個是獲取錯誤內容,一個是錯誤位置
throw new PDOException($e->getMessage(), $e->getCode());
}
}else{
return $this->pdo;
}
}
```
這也,我們就在實例化的時候實例化好了數據庫操作類!
下面封裝了一些常用的sql操作方法
### 大家可以直接使用
### 大家可以直接使用
### 大家可以直接使用
```
<?php
namespace Db;
use PDOException;
use PDO;
/**
* Created by PhpStorm.
* User: Wei
* Date: 2017/5/22
* Time: 9:12
*/
class DbDriver extends PDOException
{
protected $config;
private $pdo;
public $lastSql = '';
/**
* 事務開啟狀態
* @var
*/
public $Transactions = false;
function __construct()
{
if(empty($this->pdo)){
include_once "../../Lib/function.php";
$config = load_config('../../Config/config.php');
$this->config = $config;
$dsn = 'mysql:dbname=' . $this->config["DBNAME"] . ';host=' . $this->config["HOST"] . '';
try {
$this->pdo = new PDO($dsn, $this->config["USER"], $this->config["PWD"], array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
));
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$this->bConnected = true;
} catch (PDOException $e) {
throw new PDOException($e->getMessage(), $e->getCode());
}
}else{
return $this->pdo;
}
}
/**
* 關閉鏈接
*/
public function closeConnect()
{
$this->pdo = null;
}
/**
* 轉義字符串
* @param $string
* @return bool
* @throws Exception
*/
public function escapeString($string)
{
//參數分析
if (!$string) {
throw new Exception('$string parameter is null');
}
$_quoteString = $this->pdo->quote($string);
if ($_quoteString === false) {
throw new Exception('the driver does not support quoting in this way');
} else {
return $_quoteString;
}
}
/**
* 獲取數據庫錯誤信息
* @return mixed
*/
public function errorMsg()
{
$info = $this->pdo->errorInfo();
return $info[2];
}
/**
* 獲取數據庫錯誤信息代碼
*
* @access public
* @return int
*/
public function errorNum()
{
return $this->pdo->errorCode();
}
/**
* 得到插入id
* @return string
*/
public function lastInsertId()
{
return $this->pdo->lastInsertId();
}
/**
* 得到最近執行的一條sql語句
* @return string
*/
public function getLastSql()
{
return $this->lastSql;
}
/**
* 開始事務
* @return bool
*/
public function startTrans()
{
if ($this->Transactions == false) {
$this->pdo->beginTransaction();
$this->Transactions = true;
}
return true;
}
/**
* 提交事務
* @return bool
*/
public function commit()
{
if ($this->Transactions == true) {
if ($this->pdo->commit()) {
$this->Transactions = false;
}
}
return true;
}
/**
* 事務回滾
*/
public function rollback()
{
if ($this->Transactions == true) {
if ($this->pdo->rollBack()) {
$this->Transactions = false;
}
}
}
/**
* @param $sql
* @return PDOStatement
* @throws Exception|boolean
*/
public function query($sql)
{
if (!$sql) {
throw new Exception('sql parameter is null');
}
$this->lastSql = $sql;
$result = $this->pdo->query($sql);//返回 true or false
return $result->fetch(PDO::FETCH_ASSOC);;
}
/**
* 返回執行sql后影響的行數
* @param $sql
* @return int
* @throws Exception
*/
public function exec($sql)
{
if (!$sql) {
throw new Exception('sql parameter is null');
}
$this->lastSql = $sql;
$result = $this->pdo->exec($sql);
return $result;
}
public function getRow($sql)
{
if (!$sql) {
throw new Exception('sql parameter is null');
}
$this->lastSql = $sql;
$result = $this->pdo->query($sql);
if ($result === false) {
throw new Exception('sql execute failed ' . $this->getLastSql());
}
$row = $result->fetch(PDO::FETCH_ASSOC);
$result = null;
return $row;
}
public function getAll($sql)
{
if (!$sql) {
throw new Exception('sql parameter is null');
}
$this->lastSql = $sql;
$result = $this->pdo->query($sql);
if ($result === false) {
throw new Exception('sql execute failed ' . $this->getLastSql());
}
return $result->fetchAll(PDO::FETCH_ASSOC);
}
/**
* @param $table
* @param $arr_data
* @return bool
* @throws Exception
*/
public function insert($table, $arr_data)
{
if (!$table || !$arr_data) {
throw new Exception('table name and arr_data are null');
}
$keys_arr = [];
$values_arr = [];
$replace_values = [];
foreach ($arr_data as $key => $value) {
$keys_arr[] = '`' . $key . '`';
$values_arr[] = ':' . $key;
$replace_values[':' . $key] = $value;
}
$keys_str = implode(',', $keys_arr);
$values_str = implode(',', $values_arr);
$sql = sprintf('insert into `%s` (%s) values (%s)', $table, $keys_str, $values_str);
$this->lastSql = $sql;
$statement = $this->pdo->prepare($sql);
return $statement->execute($replace_values);
}
public function delete($table, $sql_where)
{
if (!$table || !$sql_where) {
throw new Exception('table name and sql_where are null');
}
$sql = sprintf('delete from `%s` where %s', $table, $sql_where);
$this->lastSql = $sql;
$result = $this->pdo->exec($sql);
if ($result === false) {
throw new Exception('sql execute failed ' . $this->getLastSql());
}
return $result;
}
public function update($table, $set, $sql_where)
{
if (!$table || !$sql_where) {
throw new Exception('table name and sql_where are null');
}
$sql = sprintf('update `%s` %s %s', $table, $set, $sql_where);
$this->lastSql = $sql;
$result = $this->pdo->exec($sql);
if ($result === false) {
throw new Exception('sql execute failed ' . $this->getLastSql());
}
return $result;
}
public function select($fields = '*', $table, $sql_where)
{
$fields_str = "*";
$fields_arr = [];
$temp = [];
if ($fields != '*' && !empty($fields)) {
$fields_arr = explode(',', $fields);
foreach ($fields_arr as $k => $v) {
$temp[] = '`' . $v . '`';
}
$fields_str = implode(',', $temp);
}else{
$fields_arr = "*";
}
if(!empty($sql_where)){
$sql = sprintf('select %s from %s where %s ', $fields_str, $table, $sql_where);
}else{
$sql = sprintf('select %s from ', $fields_str, $table);
}
$this->lastSql = $sql;
$result = $this->pdo->query($sql);
if ($result === false) {
throw new Exception('sql execute failed ' . $this->getLastSql());
}
return $this->fetch($result);
}
protected function fetch($result){
return $result->fetchAll(PDO::FETCH_ASSOC);
}
}
```
下面貼出來如何調用這個類
```
include "DbDriver.php";
$config = array(
//'配置項'=>'配置值'
'TYPE'=>'mysql',
'HOST'=>'127.0.0.1',
'DBNAME'=>'myblog',
'USER'=>'root',
'PWD'=>'root',
'PORT'=>'3306',
);
$pdo = new DbDriver($config);
$res = $pdo->select("id",'admin','');
echo $pdo->errorInfo();
var_dump($res);die;
```
- 一、php封裝pdo操作類
- 二、PHP 3des 加密類
- 三、PHP 調用webserver服務器詳解
- 四、命名空間的USE 和 require include require_once include_once詳解
- 五、thinkphp集成小米推送
- 六、PHP實現上傳文件進度條
- 七、PHP根據地址新建路徑下載地址文件
- 八、PHP使用AJAX上傳圖片即時預覽
- 九、強制CDN更新靜態資源文件
- 十、THINKPHP集成支付寶APP支付并提供接口
- 十一、THINKPHP集成支付寶APP支付 錯誤詳解 支付寶APP支付 顯示 系統繁忙 請稍后再試 ALI40247 dengg
- 十二、PHP生成二維碼圖片或帶logo的二維碼
- 十三、蛋疼的bom頭 惡心了我好久[json無法解析]
- 十四、php windows安裝imagick擴展
- 十五、windows下Composer的安裝與使用
- 十六、[2017]最新支付寶wap支付集成THINKPHP3.2.3 demo
- 十七、VUE.JS 安裝與發布
- 十八、PHP 執行 linux 命令行 操作示例
- 十九、關于CSP 減少XSS攻擊的介紹