栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

PHP的PDO常用类库实例分析

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

PHP的PDO常用类库实例分析

本文实例讲述了PHP的PDO常用类库。分享给大家供大家参考,具体如下:

1、Db.class.php 连接数据库

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 数据库操作类

_db = Db::getDB();
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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());
    }
  }
  
  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;
  }
  
  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, ',');
  }
  
  private function getError($fun, $line) {
    return __CLASS__ . '->' . $fun . '() line'. $line .' ERROR!';
  }
  
  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程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/43573.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号