当前位置:Gxlcms > PHP教程 > php中PDO方式实现数据库的增删改查示例代码

php中PDO方式实现数据库的增删改查示例代码

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

PDO是mysql数据库操作的一个公用类了,我们不需要进行自定类就可以直接使用pdo来操作数据库了,但是在php默认配置中pdo是未开启所以我们必须先在php.ini中开启它才可以使用。

需要开启php的pdo支持,php5.1以上版本支持

实现数据库连接单例化,有三要素 静态变量、静态实例化方法、私有构造函数 DPDO.php

  1. class DPDO{
  2. private $DSN;
  3. private $DBUser;
  4. private $DBPwd;
  5. private $longLink;
  6. private $pdo;
  7. //私有构造函数 防止被直接实例化
  8. private function construct($dsn, $DBUser, $DBPwd, $longLink = false) {
  9. $this->DSN = $dsn;
  10. $this->DBUser = $DBUser;
  11. $this->DBPwd = $DBPwd;
  12. $this->longLink = $longLink;
  13. $this->connect();
  14. }
  15. //私有 空克隆函数 防止被克隆
  16. private function clone(){}
  17. //静态 实例化函数 返回一个pdo对象
  18. static public function instance($dsn, $DBUser, $DBPwd, $longLink = false){
  19. static $singleton = array();//静态函数 用于存储实例化对象
  20. $singIndex = md5($dsn . $DBUser . $DBPwd . $longLink);
  21. if (empty($singleton[$singIndex])) {
  22. $singleton[$singIndex] = new self($dsn, $DBUser, $DBPwd, $longLink = false);
  23. }
  24. return $singleton[$singIndex]->pdo;
  25. }
  26. private function connect(){
  27. try{
  28. if($this->longLink){
  29. $this->pdo = new PDO($this->DSN, $this->DBUser, $this->DBPwd, array(PDO::ATTR_PERSISTENT => true));
  30. }else{
  31. $this->pdo = new PDO($this->DSN, $this->DBUser, $this->DBPwd);
  32. }
  33. $this->pdo->query('SET NAMES UTF-8');
  34. } catch(PDOException $e) {
  35. die('Error:' . $e->getMessage() . '<br/>');
  36. }
  37. }
  38. }

用于处理字段映射,使用pdo的字段映射,可以有效避免sql注入

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

增删改查的具体实现DB.php

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

测试文件test.php

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

以上就是php中PDO方式实现数据库的增删改查示例代码的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行