本文实例讲述了PHP的PDO常用类库。分享给大家供大家参考,具体如下:
1、Db.class.php 连接数据库
<?php // 连接数据库 class Db { static public function getDB() { try { $pdo = new PDO(DB_DSN, DB_USER, DB_PWD); $pdo->setAttribute(PDO::ATTR_PERSISTENT, true); // 设置数据库连接为持久连接 $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // 设置抛出错误 $pdo->setAttribute(PDO::ATTR_ORACLE_NULLS, true); // 设置当字符串为空转换为 SQL 的 NULL $pdo->query('SET NAMES utf8'); // 设置数据库编码 } catch (PDOException $e) { exit('数据库连接错误,错误信息:'. $e->getMessage()); } return $pdo; } } ?>
2、Model.class.php 数据库操作类
<?php /** * 数据库操作类库 * author Lee. * Last modify $Date: 2012-1-19 13:59;04 $ */ class M { private $_db; //数据库句柄 public $_sql; //SQL语句 /** * 构造方法 */ public function __construct() { $this->_db = Db::getDB(); } /** * 数据库添加操作 * @param string $tName 表名 * @param array $field 字段数组 * @param array $val 值数组 * @param bool $is_lastInsertId 是否返回添加ID * @return int 默认返回成功与否,$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()); } } /** * 数据库修改操作 * @param string $tName 表名 * @param array $field 字段数组 * @param array $val 值数组 * @param string $condition 条件 * @return int 受影响的行数 */ 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()); } } /** * 数据库删除操作(注:必须添加 where 条件) * @param string $tName 表名 * @param string $condition 条件 * @return int 受影响的行数 */ 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()); } } /** * 返回表总个数 * @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()); } } /** * 数据库删除多条数据 * @param string $tName 表名 * @param string $field 依赖字段 * @param array $ids 删除数组 * @return int 受影响的行数 */ 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()); } } /** * 获取表格的最后主键(注:针对 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()); } } /** * 检查数据是否已经存在(依赖条件) * @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()); } } /** * 检查数据是否已经存在(依赖 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()); } } /** * 预处理删除(注:针对主键为 INT 类型,推荐使用) * @param string $tName 表名 * @param string $primary 主键字段 * @param int or array or string $ids 如果是删除一条为 INT,多条为 array,删除一个范围为 string * @return int 返回受影响的行数 */ 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()); } } /** * 返回单个字段数据或单条记录 * @param string $tName 表名 * @param string $condition 条件 * @param string or array $fields 返回的字段,默认是* * @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()); } } /** * 返回多条数据 * @param string $tName 表名 * @param string $fields 返回字段,默认为* * @param string $condition 条件 * @param string $order 排序 * @param string $limit 显示个数 * @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()); } } /** * 格式化数组(表结构和值) * @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; } /** * 格式化问号 * @param int $count 数量 * @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, ','); } /** * 错误提示 * @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, '`') . '`'; } /** * 析构方法 */ public function __destruct() { $this->_db = null; } }
更多关于PHP相关内容感兴趣的读者可查看本站专题:《php curl用法总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php操作office文档技巧总结(包括word,excel,access,ppt)》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家PHP程序设计有所帮助。

PHP在現代Web開發中仍然重要,尤其在內容管理和電子商務平台。 1)PHP擁有豐富的生態系統和強大框架支持,如Laravel和Symfony。 2)性能優化可通過OPcache和Nginx實現。 3)PHP8.0引入JIT編譯器,提升性能。 4)雲原生應用通過Docker和Kubernetes部署,提高靈活性和可擴展性。

PHP適合web開發,特別是在快速開發和處理動態內容方面表現出色,但不擅長數據科學和企業級應用。與Python相比,PHP在web開發中更具優勢,但在數據科學領域不如Python;與Java相比,PHP在企業級應用中表現較差,但在web開發中更靈活;與JavaScript相比,PHP在後端開發中更簡潔,但在前端開發中不如JavaScript。

PHP和Python各有優勢,適合不同場景。 1.PHP適用於web開發,提供內置web服務器和豐富函數庫。 2.Python適合數據科學和機器學習,語法簡潔且有強大標準庫。選擇時應根據項目需求決定。

PHP是一種廣泛應用於服務器端的腳本語言,特別適合web開發。 1.PHP可以嵌入HTML,處理HTTP請求和響應,支持多種數據庫。 2.PHP用於生成動態網頁內容,處理表單數據,訪問數據庫等,具有強大的社區支持和開源資源。 3.PHP是解釋型語言,執行過程包括詞法分析、語法分析、編譯和執行。 4.PHP可以與MySQL結合用於用戶註冊系統等高級應用。 5.調試PHP時,可使用error_reporting()和var_dump()等函數。 6.優化PHP代碼可通過緩存機制、優化數據庫查詢和使用內置函數。 7

PHP成為許多網站首選技術棧的原因包括其易用性、強大社區支持和廣泛應用。 1)易於學習和使用,適合初學者。 2)擁有龐大的開發者社區,資源豐富。 3)廣泛應用於WordPress、Drupal等平台。 4)與Web服務器緊密集成,簡化開發部署。

PHP在現代編程中仍然是一個強大且廣泛使用的工具,尤其在web開發領域。 1)PHP易用且與數據庫集成無縫,是許多開發者的首選。 2)它支持動態內容生成和麵向對象編程,適合快速創建和維護網站。 3)PHP的性能可以通過緩存和優化數據庫查詢來提升,其廣泛的社區和豐富生態系統使其在當今技術棧中仍具重要地位。

在PHP中,弱引用是通過WeakReference類實現的,不會阻止垃圾回收器回收對象。弱引用適用於緩存系統和事件監聽器等場景,需注意其不能保證對象存活,且垃圾回收可能延遲。

\_\_invoke方法允許對象像函數一樣被調用。 1.定義\_\_invoke方法使對象可被調用。 2.使用$obj(...)語法時,PHP會執行\_\_invoke方法。 3.適用於日誌記錄和計算器等場景,提高代碼靈活性和可讀性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

SAP NetWeaver Server Adapter for Eclipse
將Eclipse與SAP NetWeaver應用伺服器整合。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

記事本++7.3.1
好用且免費的程式碼編輯器

Atom編輯器mac版下載
最受歡迎的的開源編輯器