当前位置:Gxlcms > 数据库问题 > [实例]php中PDO方式实现数据库的增删改查

[实例]php中PDO方式实现数据库的增删改查

时间:2021-07-01 10:21:17 帮助过:22人阅读

整理的比较容易理解的PDO操作实例,注意,需要开启php的pdo支持,php5.1以上版本支持实现数据库连接单例化,有三要素 静态变量、静态实例化方法、私有构造函数 DPDO.php
  1. //PDO操作类
  2. //author http://www.lai18.com
  3. class DPDO{
  4. private $DSN;
  5. private $DBUser;
  6. private $DBPwd;
  7. private $longLink;
  8. private $pdo;
  9. //私有构造函数 防止被直接实例化
  10. private function __construct($dsn, $DBUser, $DBPwd, $longLink = false) {
  11. $this->DSN = $dsn;
  12. $this->DBUser = $DBUser;
  13. $this->DBPwd = $DBPwd;
  14. $this->longLink = $longLink;
  15. $this->connect();
  16. }
  17. //私有 空克隆函数 防止被克隆
  18. private function __clone(){}
  19. //静态 实例化函数 返回一个pdo对象
  20. static public function instance($dsn, $DBUser, $DBPwd, $longLink = false){
  21. static $singleton = array();//静态函数 用于存储实例化对象
  22. $singIndex = md5($dsn . $DBUser . $DBPwd . $longLink);
  23. if (empty($singleton[$singIndex])) {
  24. $singleton[$singIndex] = new self($dsn, $DBUser, $DBPwd, $longLink = false);
  25. }
  26. return $singleton[$singIndex]->pdo;
  27. }
  28. private function connect(){
  29. try{
  30. if($this->longLink){
  31. $this->pdo = new PDO($this->DSN, $this->DBUser, $this->DBPwd, array(PDO::ATTR_PERSISTENT => true));
  32. }else{
  33. $this->pdo = new PDO($this->DSN, $this->DBUser, $this->DBPwd);
  34. }
  35. $this->pdo->query(‘SET NAMES UTF-8‘);
  36. } catch(PDOException $e) {
  37. die(‘Error:‘ . $e->getMessage() . ‘<br/>‘);
  38. }
  39. }
  40. }


用于处理字段映射,使用pdo的字段映射,可以有效避免sql注入
  1. //字段关联数组处理, 主要用于写入和更新数据、同and 或 or 的查询条件,产生sql语句和映射字段的数组
  2. //author http://www.lai18.com
  3. public function FDFields($data, $link = ‘,‘, $judge = array(), $aliasTable = ‘‘){
  4. $sql = ‘‘;
  5. $mapData = array();
  6. foreach($data as $key => $value) {
  7. $mapIndex = ‘:‘ . ($link != ‘,‘ ? ‘c‘ : ‘‘) . $aliasTable . $key;
  8. $sql .= ‘ ‘ . ($aliasTable ? $aliasTable . ‘.‘ : ‘‘) . ‘`‘ . $key . ‘` ‘ . ($judge[$key] ? $judge[$key] : ‘=‘) . ‘ ‘ . $mapIndex . ‘ ‘ . $link;
  9. $mapData[$mapIndex] = $value;
  10. }
  11. $sql = trim($sql, $link);
  12. return array($sql, $mapData);
  13. }
  14. //用于处理单个字段处理
  15. public function FDField($field, $value, $judge = ‘=‘, $preMap = ‘cn‘, $aliasTable = ‘‘) {
  16. $mapIndex = ‘:‘ . $preMap . $aliasTable . $field;
  17. $sql = ‘ ‘ . ($aliasTable ? $aliasTable . ‘.‘ : ‘‘) . ‘`‘ . $field . ‘`‘ . $judge . $mapIndex;
  18. $mapData[$mapIndex] = $value;
  19. return array($sql, $mapData);
  20. }
  21. //使用刚方法可以便捷产生查询条件及对应数据数组
  22. public function FDCondition($condition, $mapData) {
  23. if(is_string($condition)) {
  24. $where = $condition;
  25. } else if (is_array($condition)) {
  26. if($condition[‘str‘]) {
  27. if (is_string($condition[‘str‘])) {
  28. $where = $condition[‘str‘];
  29. } else {
  30. return false;
  31. }
  32. }
  33. if(is_array($condition[‘data‘])) {
  34. $link = $condition[‘link‘] ? $condition[‘link‘] : ‘and‘;
  35. list($conSql, $mapConData) = $this->FDFields($condition[‘data‘], $link, $condition[‘judge‘]);
  36. if ($conSql) {
  37. $where .= ($where ? ‘ ‘ . $link : ‘‘) . $conSql;
  38. $mapData = array_merge($mapData, $mapConData);
  39. }
  40. }
  41. }
  42. return array($where, $mapData);
  43. }


增删改查的具体实现DB.php
  1. //数据库的遍历
  2. //author http://www.lai18.com
  3. public function fetch($sql, $searchData = array(), $dataMode = PDO::FETCH_ASSOC, $preType = array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)) {
  4. if ($sql) {
  5. $sql .= ‘ limit 1‘;
  6. $pdoStatement = $this->pdo->prepare($sql, $preType);
  7. $pdoStatement->execute($searchData);
  8. return $data = $pdoStatement->fetch($dataMode);
  9. } else {
  10. return false;
  11. }
  12. }
  13. public function fetchAll($sql, $searchData = array(), $limit = array(0, 10), $dataMode = PDO::FETCH_ASSOC, $preType = array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)) {
  14. if ($sql) {
  15. $sql .= ‘ limit ‘ . (int) $limit[0] . ‘,‘ . (intval($limit[1]) > 0 ? intval($limit[1]) : 10);
  16. $pdoStatement = $this->pdo->prepare($sql, $preType);
  17. $pdoStatement->execute($searchData);
  18. return $data = $pdoStatement->fetchAll($dataMode);
  19. } else {
  20. return false;
  21. }
  22. }
  23. public function insert($tableName, $data, $returnInsertId = false, $replace = false) {
  24. if(!empty($tableName) && count($data) > 0){
  25. $sql = $replace ? ‘REPLACE INTO ‘ : ‘INSERT INTO ‘;
  26. list($setSql, $mapData) = $this->FDFields($data);
  27. $sql .= $tableName . ‘ set ‘ . $setSql;
  28. $pdoStatement = $this->pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
  29. $execRet = $pdoStatement->execute($mapData);
  30. return $execRet ? ($returnInsertId ? $this->pdo->lastInsertId() : $execRet) : false;
  31. } else {
  32. return false;
  33. }
  34. }
  35. public function update($tableName, $data, $condition, $mapData = array(), $returnRowCount = true) {
  36. if(!empty($tableName) && count($data) > 0) {
  37. $sql = ‘UPDATE ‘ . $tableName . ‘ SET ‘;
  38. list($setSql, $mapSetData) = $this->FDFields($data);
  39. $sql .= $setSql;
  40. $mapData = array_merge($mapData, $mapSetData);
  41. list($where, $mapData) = $this->FDCondition($condition, $mapData);
  42. $sql .= $where ? ‘ WHERE ‘ . $where : ‘‘;
  43. $pdoStatement = $this->pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
  44. $execRet = $pdoStatement->execute($mapData);
  45. return $execRet ? ($returnRowCount ? $pdoStatement->rowCount() : $execRet) : false;
  46. } else {
  47. return false;
  48. }
  49. }
  50. public function delete($tableName, $condition, $mapData = array()) {
  51. if(!empty($tableName) && $condition){
  52. $sql = ‘DELETE FROM ‘ . $tableName;
  53. list($where, $mapData) = $this->FDCondition($condition, $mapData);
  54. $sql .= $where ? ‘ WHERE ‘ . $where : ‘‘;
  55. $pdoStatement = $this->pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
  56. $execRet = $pdoStatement->execute($mapData);
  57. return $execRet;
  58. }
  59. }


测试文件test.php
  1. //PDO操作类-测试PHP示例
  2. //author http://www.lai18.com
  3. header("Content-type: text/html; charset=utf-8");
  4. define(‘APP_DIR‘, dirname(__FILE__));
  5. if (function_exists(‘spl_autoload_register‘)) {
  6. spl_autoload_register(‘autoClass‘);
  7. } else {
  8. function __auto_load($className){
  9. autoClass($className);
  10. }
  11. }
  12. function autoClass($className){
  13. try{
  14. require_once APP_DIR.‘/class/‘.$className.‘.php‘;
  15. } catch (Exception $e) {
  16. die(‘Error:‘ . $e->getMessage() . ‘<br />‘);
  17. }
  18. }
  19. $DB = new DB();
  20. //插入
  21. $inData[‘a‘] = rand(1, 100);
  22. $inData[‘b‘] = rand(1, 1000);
  23. $inData[‘c‘] = rand(1,200) . ‘.‘ . rand(1,100);
  24. $ret = $DB->insert(‘a‘, $inData);
  25. echo ‘插入‘ . ($ret ? ‘成功‘ : ‘失败‘) . ‘<br/>‘;
  26. //更新
  27. $upConData[‘a‘] = 100;
  28. $upConJudge[‘a‘] = ‘<‘;
  29. $upConData[‘b‘] = 30;
  30. $upConJudge[‘b‘] = ‘>‘;
  31. list($upConStr, $mapUpConData) = $DB->FDField(‘b‘, 200, ‘<‘, ‘gt‘);
  32. $condition = array(
  33. ‘str‘ => $upConStr,
  34. ‘data‘ => $upConData,
  35. ‘judge‘ => $upConJudge,
  36. ‘link‘ => ‘and‘
  37. );
  38. $upData[‘a‘] = rand(1, 10);
  39. $upData[‘b‘] = 1;
  40. $upData[‘c‘] = 1.00;
  41. $changeRows = $DB->update(‘a‘, $upData, $condition, $mapUpConData);
  42. echo ‘更新行数:‘ . (int) $changeRows . ‘<br/>‘;
  43. //删除
  44. $delVal = rand(1, 10);
  45. list($delCon, $mapDelCon) = $DB->FDField(‘a‘, $delVal);
  46. $delRet = $DB->delete(‘a‘, $delCon, $mapDelCon);
  47. echo ‘删除a=‘ . $delVal . ($delRet ? ‘成功‘ : ‘失败‘) . ‘<br/>‘;
  48. //查询
  49. $data[‘a‘] = ‘10‘;
  50. $judge[‘a‘] = ‘>‘;
  51. $data[‘b‘] = ‘400‘;
  52. $judge[‘b‘] = ‘<‘;
  53. list($conSql, $mapConData) = $DB->FDFields($data, ‘and‘, $judge);
  54. $mData = $DB->fetch(‘select * from a where ‘ . $conSql . ‘ order by `a` desc‘, $mapConData);
  55. var_dump($mData);


以上所述就是本文的全部内容了,希望大家能够喜欢。 

参考来源: 
php中PDO方式实现数据库的增删改查
http://www.lai18.com/content/422492.html

[实例]php中PDO方式实现数据库的增删改查

标签:php   pdo   数据库   

人气教程排行