PHP的PDO常用類庫(kù)實(shí)例分析
本文實(shí)例講述了PHP的PDO常用類庫(kù)。分享給大家供大家參考,具體如下:
1、Db.class.php 連接數(shù)據(jù)庫(kù)
<?php // 連接數(shù)據(jù)庫(kù) class Db { static public function getDB() { try { $pdo = new PDO(DB_DSN, DB_USER, DB_PWD); $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 設(shè)置數(shù)據(jù)庫(kù)連接為持久連接 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 設(shè)置拋出錯(cuò)誤 $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 設(shè)置當(dāng)字符串為空轉(zhuǎn)換為 SQL 的 NULL $pdo->query('SET NAMES utf8'); // 設(shè)置數(shù)據(jù)庫(kù)編碼 } catch (PDOException $e) { exit('數(shù)據(jù)庫(kù)連接錯(cuò)誤,錯(cuò)誤信息:'. $e->getMessage()); } return $pdo; } } ?>
2、Model.class.php 數(shù)據(jù)庫(kù)操作類
<?php /** * 數(shù)據(jù)庫(kù)操作類庫(kù) * author Lee. * Last modify $Date: 2012-1-19 13:59;04 $ */ class M { private $_db; //數(shù)據(jù)庫(kù)句柄 public $_sql; //SQL語句 /** * 構(gòu)造方法 */ public function __construct() { $this->_db = Db::getDB(); } /** * 數(shù)據(jù)庫(kù)添加操作 * @param string $tName 表名 * @param array $field 字段數(shù)組 * @param array $val 值數(shù)組 * @param bool $is_lastInsertId 是否返回添加ID * @return int 默認(rèn)返回成功與否,$is_lastInsertId 為true,返回添加ID */ public function insert($tName, $fields, $vals, $is_lastInsertId=FALSE) { try { if (!is_array($fields) || !is_array($vals)) exit($this->getError(__FUNCTION__, __LINE__)); $fields = $this->formatArr($fields); $vals = $this->formatArr($vals, false); $tName = $this->formatTabName($tName); $this->_sql = "INSERT INTO {$tName} ({$fields}) VALUES ({$vals})"; if (!$is_lastInsertId) { $row = $this->_db->exec($this->_sql); return $row; } else { $this->_db->exec($this->_sql); $lastId = (int)$this->_db->lastInsertId(); return $lastId; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 數(shù)據(jù)庫(kù)修改操作 * @param string $tName 表名 * @param array $field 字段數(shù)組 * @param array $val 值數(shù)組 * @param string $condition 條件 * @return int 受影響的行數(shù) */ public function update($tName, $fieldVal, $condition) { try { if (!is_array($fieldVal) || !is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $upStr = ''; foreach ($fieldVal as $k=>$v) { $upStr .= '`'.$k . '`=' . '\'' . $v . '\'' . ','; } $upStr = rtrim($upStr, ','); $this->_sql = "UPDATE {$tName} SET {$upStr} WHERE {$condition}"; $row = $this->_db->exec($this->_sql); return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 數(shù)據(jù)庫(kù)刪除操作(注:必須添加 where 條件) * @param string $tName 表名 * @param string $condition 條件 * @return int 受影響的行數(shù) */ public function del($tName, $condition) { try { if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $tName= $this->formatTabName($tName); $this->_sql = "DELETE FROM {$tName} WHERE {$condition}"; $row = $this->_db->exec($this->_sql); return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回表總個(gè)數(shù) * @param string $tName 表名 * @param string $condition 條件 * @return int */ public function total($tName, $condition='') { try { if (!is_string($tName)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT COUNT(*) AS total FROM {$tName}" . ($condition=='' ? '' : ' WHERE ' . $condition); $re = $this->_db->query($this->_sql); foreach ($re as $v) { $total = $v['total']; } return (int)$total; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 數(shù)據(jù)庫(kù)刪除多條數(shù)據(jù) * @param string $tName 表名 * @param string $field 依賴字段 * @param array $ids 刪除數(shù)組 * @return int 受影響的行數(shù) */ public function delMulti($tName, $field, $ids) { try { if (!is_string($tName) || !is_array($ids)) exit($this->getError(__FUNCTION__, __LINE__)); $delStr = ''; $tName = $this->formatTabName($tName); $field = $this->formatTabName($field); foreach ($ids as $v) { $delStr .= $v . ','; } $delStr = rtrim($delStr, ','); $this->_sql = "DELETE FROM {$tName} WHERE {$field} IN ({$delStr})"; $row = $this->_db->exec($this->_sql); return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 獲取表格的最后主鍵(注:針對(duì) INT 類型) * @param string $tName 表名 * @return int */ public function insertId($tName) { try { if (!is_string($tName)) exit($this->getError(__FUNCTION__, __LINE__)); $this->_sql = "SHOW TABLE STATUS LIKE '{$tName}'"; $result = $this->_db->query($this->_sql); $insert_id = 0; foreach ($result as $v) { $insert_id = $v['Auto_increment']; } return (int)$insert_id; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 檢查數(shù)據(jù)是否已經(jīng)存在(依賴條件) * @param string $tName 表名 * @param string $field 依賴的字段 * @return bool */ public function exists($tName, $condition) { try { if (!is_string($tName) || !is_string($condition)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$condition}"; $result = $this->_db->query($this->_sql); foreach ($result as $v) { $b = $v['total']; } if ($b) { return true; } else { return false; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 檢查數(shù)據(jù)是否已經(jīng)存在(依賴 INT 主鍵) * @param string $tName 表名 * @param string $primary 主鍵 * @param int $id 主鍵值 * @return bool */ public function existsByPK($tName, $primary, $id) { try { if (!is_string($tName) || !is_string($primary) || !is_int($id)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT COUNT(*) AS total FROM {$tName} WHERE {$primary} = ". $id; $result = $this->_db->query($this->_sql); foreach ($result as $v) { $b = $v['total']; } if ($b) { return true; } else { return false; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 預(yù)處理刪除(注:針對(duì)主鍵為 INT 類型,推薦使用) * @param string $tName 表名 * @param string $primary 主鍵字段 * @param int or array or string $ids 如果是刪除一條為 INT,多條為 array,刪除一個(gè)范圍為 string * @return int 返回受影響的行數(shù) */ public function delByPK($tName, $primary, $ids, $mult=FALSE) { try { if (!is_string($tName) || !is_string($primary) || (!is_int($ids) && !is_array($ids) && !is_string($ids)) || !is_bool($mult)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $stmt = $this->_db->prepare("DELETE FROM {$tName} WHERE {$primary}=?"); if (!$mult) { $stmt->bindParam(1, $ids); $row = $stmt->execute(); } else { if (is_array($ids)) { $row = 0; foreach ($ids as $v) { $stmt->bindParam(1, $v); if ($stmt->execute()) { $row++; } } } elseif (is_string($ids)) { if (!strpos($ids, '-')) exit($this->getError(__FUNCTION__, __LINE__)); $split = explode('-', $ids); if (count($split)!=2 || $split[0]>$split[1]) exit($this->getError(__FUNCTION__, __LINE__)); $i = null; $count = $split[1]-$split[0]+1; for ($i=0; $i<$count; $i++) { $idArr[$i] = $split[0]++; } $idStr = ''; foreach ($idArr as $id) { $idStr .= $id . ','; } $idStr = rtrim($idStr, ','); $this->_sql ="DELETE FROM {$tName} WHERE {$primary} in ({$idStr})"; $row = $this->_db->exec($this->_sql); } } return $row; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回單個(gè)字段數(shù)據(jù)或單條記錄 * @param string $tName 表名 * @param string $condition 條件 * @param string or array $fields 返回的字段,默認(rèn)是* * @return string || array */ public function getRow($tName, $condition='', $fields="*") { try { if (!is_string($tName) || !is_string($condition) || !is_string($fields) || empty($fields)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $this->_sql = "SELECT {$fields} FROM {$tName} "; $this->_sql .= ($condition=='' ? '' : "WHERE {$condition}") . " LIMIT 1"; $sth = $this->_db->prepare($this->_sql); $sth->execute(); $result = $sth->fetch(PDO::FETCH_ASSOC); if ($fields === '*') { return $result; } else { return $result[$fields]; } } catch (PDOException $e) { exit($e->getMessage()); } } /** * 返回多條數(shù)據(jù) * @param string $tName 表名 * @param string $fields 返回字段,默認(rèn)為* * @param string $condition 條件 * @param string $order 排序 * @param string $limit 顯示個(gè)數(shù) * @return PDOStatement */ public function getAll($tName, $fields='*', $condition='', $order='', $limit='') { try { if (!is_string($tName) || !is_string($fields) || !is_string($condition) || !is_string($order) || !is_string($limit)) exit($this->getError(__FUNCTION__, __LINE__)); $tName = $this->formatTabName($tName); $fields = ($fields=='*' || $fields=='') ? '*' : $fields; $condition = $condition=='' ? '' : " WHERE ". $condition ; $order = $order=='' ? '' : " ORDER BY ". $order; $limit = $limit=='' ? '' : " LIMIT ". $limit; $this->_sql = "SELECT {$fields} FROM {$tName} {$condition} {$order} {$limit}"; $sth = $this->_db->prepare($this->_sql); $sth->execute(); $result = $sth->fetchAll(PDO::FETCH_ASSOC); return $result; } catch (PDOException $e) { exit($e->getMessage()); } } /** * 格式化數(shù)組(表結(jié)構(gòu)和值) * @param array $field * @param bool $isField * @return string */ private function formatArr($field, $isField=TRUE) { if (!is_array($field)) exit($this->getError(__FUNCTION__, __LINE__)); $fields = ''; if ($isField) { foreach ($field as $v) { $fields .= '`'.$v.'`,'; } } else { foreach ($field as $v) { $fields .= '\''.$v.'\''.','; } } $fields = rtrim($fields, ','); return $fields; } /** * 格式化問號(hào) * @param int $count 數(shù)量 * @return string 返回格式化后的字符串 */ private function formatMark($count) { $str = ''; if (!is_int($count)) exit($this->getError(__FUNCTION__, __LINE__)); if ($count==1) return '?'; for ($i=0; $i<$count; $i++) { $str .= '?,'; } return rtrim($str, ','); } /** * 錯(cuò)誤提示 * @param string $fun * @return string */ private function getError($fun, $line) { return __CLASS__ . '->' . $fun . '() line<font color="red">'. $line .'</font> ERROR!'; } /** * 處理表名 * @param string $tName * @return string */ private function formatTabName($tName) { return '`' . trim($tName, '`') . '`'; } /** * 析構(gòu)方法 */ public function __destruct() { $this->_db = null; } }
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《php curl用法總結(jié)》、《PHP運(yùn)算與運(yùn)算符用法總結(jié)》、《PHP網(wǎng)絡(luò)編程技巧總結(jié)》、《PHP基本語法入門教程》、《php操作office文檔技巧總結(jié)(包括word,excel,access,ppt)》、《php日期與時(shí)間用法總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。
- 全新的PDO數(shù)據(jù)庫(kù)操作類php版(僅適用Mysql)
- PHP實(shí)現(xiàn)PDO的mysql數(shù)據(jù)庫(kù)操作類
- php基于PDO實(shí)現(xiàn)功能強(qiáng)大的MYSQL封裝類實(shí)例
- PHP用PDO如何封裝簡(jiǎn)單易用的DB類詳解
- PHP基于單例模式編寫PDO類的方法
- PHP基于pdo的數(shù)據(jù)庫(kù)操作類【可支持mysql、sqlserver及oracle】
- PHP封裝的PDO數(shù)據(jù)庫(kù)操作類實(shí)例
- PHP基于PDO實(shí)現(xiàn)的SQLite操作類【包含增刪改查及事務(wù)等操作】
- PHP封裝的數(shù)據(jù)庫(kù)模型Model類完整示例【基于PDO】
- php封裝的pdo數(shù)據(jù)庫(kù)操作工具類與用法示例
相關(guān)文章
php通過ksort()函數(shù)給關(guān)聯(lián)數(shù)組按照鍵排序的方法
這篇文章主要介紹了php通過ksort()函數(shù)給關(guān)聯(lián)數(shù)組按照鍵排序的方法,實(shí)例分析了php中ksort()函數(shù)的使用技巧,需要的朋友可以參考下2015-03-03優(yōu)化使用mysql存儲(chǔ)session的php代碼
2008-01-01利用php遞歸實(shí)現(xiàn)無限分類 格式化數(shù)組的詳解
本篇文章是對(duì)使用php遞歸實(shí)現(xiàn)無限分類 格式化數(shù)組進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06PHP flush 函數(shù)使用注意事項(xiàng)
ob_flush/flush在手冊(cè)中的描述, 都是刷新輸出緩沖區(qū), 并且還需要配套使用, 所以會(huì)導(dǎo)致很多人迷惑…其實(shí), 他們倆的操作對(duì)象不同, 有些情況下, flush根本不做什么事情2016-08-08php關(guān)于array_multisort多維數(shù)組排序的使用說明
對(duì)于PHP語言中的多維數(shù)組排序時(shí)最為復(fù)雜的一個(gè)排序方式。我們?cè)趯?shí)際編碼中將會(huì)用到PHP函數(shù)array_multisort()來實(shí)現(xiàn)這一復(fù)雜的排序。2011-01-01php實(shí)現(xiàn)簽到功能的方法實(shí)例分析
這篇文章主要介紹了php實(shí)現(xiàn)簽到功能的方法,結(jié)合實(shí)例形式分析了php基于數(shù)據(jù)庫(kù)及時(shí)間判斷操作實(shí)現(xiàn)簽到功能的相關(guān)技巧,需要的朋友可以參考下2017-12-12PHP實(shí)現(xiàn)簡(jiǎn)單注冊(cè)登錄系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了PHP實(shí)現(xiàn)簡(jiǎn)單注冊(cè)登錄系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12[PHP]經(jīng)常用到的實(shí)用函數(shù)集合
[PHP]經(jīng)常用到的實(shí)用函數(shù)集合...2007-11-11