婷婷综合国产,91蜜桃婷婷狠狠久久综合9色 ,九九九九九精品,国产综合av

主頁 > 知識庫 > php封裝的pdo數(shù)據(jù)庫操作工具類與用法示例

php封裝的pdo數(shù)據(jù)庫操作工具類與用法示例

熱門標(biāo)簽:九江外呼系統(tǒng) 智能電話機器人排名前十名南京 阿里云400電話申請加工單 抖音有個地圖標(biāo)注是什么意思 保定crm外呼系統(tǒng)運營商 地下城堡2圖九地圖標(biāo)注 西區(qū)企業(yè)怎么做地圖標(biāo)注入駐 海南人工外呼系統(tǒng)有效果嗎 七魚外呼系統(tǒng)停用嗎

本文實例講述了php封裝的pdo數(shù)據(jù)庫操作工具類與用法。分享給大家供大家參考,具體如下:

?php
header("Content-Type:text/html;charset=utf-8");
class PdoMysql{
  public static $config = array();//設(shè)置連接參數(shù),配置信息
  public static $link = null;//保存連接標(biāo)識符
  public static $pconnect = false;//是否開啟長連接
  public static $dbVersion = null;//保存數(shù)據(jù)庫版本
  public static $connected = false;//判斷是否連接成功
  public static $PDOStatement = null;//保證PDOStatement對象
  public static $queryStr = null;//保存最后執(zhí)行的操作
  public static $error = null;//保存錯誤信息
  public static $lastInsertId = null;//保存上一步插入操作保存的AUTO_INCREMANT
  public static $numRows = null;//受影響記錄的條數(shù)
  /**
   * 構(gòu)造函數(shù),連接數(shù)據(jù)庫
   *
   * @param   array|string $dbConfig The database configuration
   *
   * @return   boolean    ( description_of_the_return_value )
   */
  public function __construct($dbConfig=''){
    if(!class_exists("PDO")){
      self::throw_exception("不支持PDO,請先開啟");
    }
    if(!is_array($dbConfig)){
      $dbConfig = array(
              'hostname' => 'localhost',
              'username' => 'root',
              'password' => '1234',
              'database' => 'test',
              'hostport' => '3306',
              'dbms'   => 'mysql',
              'dsn'   => 'mysql:host=localhost;dbname=test'
            );
    }
    if(empty($dbConfig['hostname'])){
      self::throw_exception("沒有定義數(shù)據(jù)庫配置,請先定義");
    }
    self::$config = $dbConfig;
    if(empty(self::$config['params'])){
      self::$config['params'] = array();
    }
    if(!isset(self::$link)){
      $configs = self::$config;
      if(self::$pconnect){
        //開啟長連接,添加到配置數(shù)組中
        $configs['params'][constant("PDO::ATTR_PERSISTENT")] = true;
      }
      try {
        self::$link = new PDO($configs['dsn'],$configs['username'],$configs['password'],$configs['params']);
      } catch (PDOException $e) {
        self::throw_exception($e->getMessage());
      }
      if(!self::$link){
        self::throw_exception("PDO連接錯誤");
        return false;
      }
      self::$link->exec("set names utf8");
      self::$dbVersion = self::$link->getAttribute(constant("PDO::ATTR_SERVER_VERSION"));
      unset($configs);
    }
  }
  /**
   * 得到所有記錄
   *
   * @param   type> $sql  The sql
   *
   * @return   type> All.
   */
  public static function getAll($sql=null){
    if($sql!=null){
      self::query($sql);
    }
    $result = self::$PDOStatement->fetchAll(constant("PDO::FETCH_ASSOC"));
    return $result;
  }
  /**
   * 得到一條記錄
   *
   * @param   type> $sql  The sql
   *
   * @return   type> The row.
   */
  public static function getRow($sql=null){
    if($sql!=null){
      self::query($sql);
    }
    $result = self::$PDOStatement->fetch(constant("PDO::FETCH_ASSOC"));
    return $result;
  }
  /**
   * 執(zhí)行增刪改操作,返回受影響記錄的條數(shù)
   *
   * @param   type>  $sql  The sql
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public static function execute($sql=null){
    $link = self::$link;
    if(!$link)return false;
    if($sql!=null){
      self::$queryStr = $sql;
    }
    if(!empty(self::$PDOStatement))self::free();
    $result = $link->exec(self::$queryStr);
    self::haveErrorThrowException();
    if($result){
      self::$lastInsertId = $link->lastInsertId();
      self::$numRows = $result;
      return $result;
    }else{
      return false;
    }
  }
  /**
   * 根據(jù)主鍵查找記錄
   *
   * @param   type> $tabName The tab name
   * @param   type> $priId  The pri identifier
   * @param   string $fields  The fields
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function findById($tabName,$priId,$fields='*'){
    $sql = 'SELECT %s FROM %s WHERE id=%d';
    return self::getRow(sprintf($sql,self::parseFields($fields),$tabName,$priId));
  }
  /**
   * 執(zhí)行普通查詢
   *
   * @param   type> $tables The tables
   * @param   type> $where  The where
   * @param   string $fields The fields
   * @param   type> $group  The group
   * @param   type> $having The having
   * @param   type> $order  The order
   * @param   type> $limit  The limit
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function find($tables,$where=null,$fields='*',$group=null,$having=null,$order=null,$limit
    =null){
    $sql = 'SELECT '.self::parseFields($fields).' FROM '.$tables
    .self::parseWhere($where)
    .self::parseGroup($group)
    .self::parseHaving($having)
    .self::parseOrder($order)
    .self::parseLimit($limit);
    $data = self::getAll($sql);
    return $data;
  }
  /**
   * 添加記錄
   *
   * @param   type> $data  The data
   * @param   type> $table The table
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function add($data,$table){
    $keys = array_keys($data);
    array_walk($keys, array('PdoMySQL','addSpecialChar'));
    $fieldsStr = join(',',$keys);
    $values = "'".join("','",array_values($data))."'";
    $sql = "INSERT {$table}({$fieldsStr}) VALUES({$values})";
    return self::execute($sql);
  }
  /**
   * 更新數(shù)據(jù)
   *
   * @param   type> $data  The data
   * @param   type> $table The table
   * @param   type> $where The where
   * @param   type> $order The order
   * @param   type> $limit The limit
   */
  public static function update($data,$table,$where=null,$order=null,$limit=null){
    $sets = '';
    foreach ($data as $key => $value) {
      $sets .= $key."='".$value."',";
    }
    $sets = rtrim($sets,',');
    $sql = "UPDATE {$table} SET {$sets}".self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit);
    echo $sql;
  }
  /**
   * 刪除數(shù)據(jù)
   *
   * @param   type> $data  The data
   * @param   type> $table The table
   * @param   type> $where The where
   * @param   type> $order The order
   * @param   type> $limit The limit
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function delete($table,$where=null,$order=null,$limit=null){
    $sql = "DELETE FROM {$table} ".self::parseWhere($where).self::parseOrder($order).self::parseLimit($limit);
    return self::execute($sql);
  }
  /**
   * 執(zhí)行查詢
   *
   * @param   string  $sql  The sql
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public static function query($sql=''){
    $link = self::$link;
    if(!$link)return false;
    //判斷之前是否有結(jié)果集,如果有的話,釋放結(jié)果集
    if(!empty(self::$PDOStatement))self::free();
    self::$queryStr = $sql;
    self::$PDOStatement = $link->prepare(self::$queryStr);
    $res = self::$PDOStatement->execute();
    self::haveErrorThrowException();
    return $res;
  }
  /**
   * 獲取最后執(zhí)行的sql
   *
   * @return   boolean The last sql.
   */
  public static function getLastSql(){
    $link = self::$link;
    if(!$link){
      return false;
    }
    return self::$queryStr;
  }
  /**
   * 獲取最后插入的ID
   *
   * @return   boolean The last insert identifier.
   */
  public static function getLastInsertId(){
    $link = self::$link;
    if(!$link){
      return false;
    }
    return self::$lastInsertId;
  }
  /**
   * 獲得數(shù)據(jù)庫的版本
   *
   * @return   boolean The database version.
   */
  public static function getDbVersion(){
    $link = self::$link;
    if(!$link){
      return false;
    }
    return self::$dbVersion;
  }
  /**
   * 得到數(shù)據(jù)庫中表
   *
   * @return   array ( description_of_the_return_value )
   */
  public static function showTables(){
    $tables = array();
    if(self::query("show tables")){
      $result = self::getAll();
      foreach ($result as $key => $value) {
        $tables[$key] = current($value);
      }
    }
    return $tables;
  }
  /**
   * 解析where條件
   *
   * @param   type> $where The where
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function parseWhere($where){
    $whereStr = '';
    if(is_string($where)!empty($where)){
      $whereStr = $where;
    }
    return empty($whereStr) ? '' : ' WHERE '.$whereStr;
  }
  /**
   * 解析group
   *
   * @param   type> $group The group
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function parseGroup($group){
    $groupStr = '';
    if(is_array($group)){
      $groupStr = implode(',', $group);
    }elseif(is_string($group)!empty($group)){
      $groupStr = $group;
    }
    return empty($groupStr) ? '' : ' GROUP BY '.$groupStr;
  }
  /**
   * 解析having
   *
   * @param   type> $having The having
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function parseHaving($having){
    $havingStr = '';
    if(is_string($having)!empty($having)){
      $havingStr = $having;
    }
    return empty($havingStr) ? '' : ' HAVING '.$havingStr;
  }
  /**
   * 解析order
   *
   * @param   type> $order The order
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function parseOrder($order){
    $orderStr = '';
    if(is_string($order)!empty($order)){
      $orderStr = $order;
    }
    return empty($orderStr) ? '' : ' ORDER BY '.$orderStr;
  }
  /**
   * 解析limit
   *
   * @param   type> $limit The limit
   *
   * @return   type> ( description_of_the_return_value )
   */
  public static function parseLimit($limit){
    $limitStr = '';
    if(is_array($limit)){
      $limitStr = implode(',', $limit);
    }elseif(is_string($limit)!empty($limit)){
      $limitStr = $limit;
    }
    return empty($limitStr) ? '' : ' LIMIT '.$limitStr;
  }
  /**
   * 解析字段
   *
   * @param   type> $fields The fields
   *
   * @return   string ( description_of_the_return_value )
   */
  public static function parseFields($fields){
    if(is_array($fields)){
      array_walk($fields, array('PdoMySQL','addSpecialChar'));
      $fieldsStr = implode(',', $fields);
    }elseif (is_string($fields)!(empty($fields))) {
      if(strpos($fields, '`')===false){
        $fields = explode(',', $fields);
        array_walk($fields, array('PdoMySQL','addSpecialChar'));
        $fieldsStr = implode(',', $fields);
      }else{
        $fieldsStr = $fields;
      }
    }else{
      $fieldsStr = "*";
    }
    return $fieldsStr; 
  }
  /**
   * 通過反引號引用字字段
   *
   * @param   string $value The value
   *
   * @return   string ( description_of_the_return_value )
   */
  public static function addSpecialChar($value){
    if($value==="*"||strpos($value,'.')!==false||strpos($value,'`')!==false){
      //不用做處理
    }elseif(strpos($value, '`')===false){
      $value = '`'.trim($value).'`';
    }
    return $value;
  }
  /**
   * 釋放結(jié)果集
   */
  public static function free(){
    self::$PDOStatement = null;
  }
  /**
   * 拋出錯誤信息
   *
   * @return   boolean ( description_of_the_return_value )
   */
  public static function haveErrorThrowException(){
    $obj = empty(self::$PDOStatement) ? self::$link : self::$PDOStatement;
    $arrError = $obj->errorInfo();
    if($arrError[0]!='00000'){
      self::$error = 'SQLSTATE=>'.$arrError[0].'br/>SQL Error=>'.$arrError[2].'br/>Error SQL=>'.self::$queryStr;
      self::throw_exception(self::$error);
      return false;
    }
    if(self::$queryStr==''){
      self::throw_exception('沒有執(zhí)行SQL語句');
      return false;
    }
  }
  /**
   * 自定義錯誤處理
   *
   * @param   type> $errMsg The error message
   */
  public static function throw_exception($errMsg){
    echo $errMsg;
  }
  /**
   * 銷毀連接對象,關(guān)閉數(shù)據(jù)庫
   */
  public static function close(){
    self::$link = null;
  }
}
$pdo = new PdoMysql();
var_dump($pdo->showTables());

更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《PHP基于pdo操作數(shù)據(jù)庫技巧總結(jié)》、《php+mysqli數(shù)據(jù)庫程序設(shè)計技巧總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》

希望本文所述對大家PHP程序設(shè)計有所幫助。

您可能感興趣的文章:
  • PHP基于MySQLI函數(shù)封裝的數(shù)據(jù)庫連接工具類【定義與用法】
  • 常用PHP封裝分頁工具類
  • php封裝的驗證碼工具類完整實例
  • PHP封裝的驗證碼工具類定義與用法示例
  • PHP抓取、分析國內(nèi)視頻網(wǎng)站的視頻信息工具類
  • PHP常用工具類大全附全部代碼下載
  • PHP實現(xiàn)基于面向?qū)ο蟮膍ysqli擴展庫增刪改查操作工具類
  • PHP實現(xiàn)可添加水印與生成縮略圖的圖片處理工具類
  • php實現(xiàn)網(wǎng)頁緩存的工具類分享
  • PHP常用的類封裝小結(jié)【4個工具類】

標(biāo)簽:韶關(guān) 遼陽 昭通 甘肅 涼山 九江 十堰 梅河口

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php封裝的pdo數(shù)據(jù)庫操作工具類與用法示例》,本文關(guān)鍵詞  php,封,裝的,pdo,數(shù)據(jù)庫,操作,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《php封裝的pdo數(shù)據(jù)庫操作工具類與用法示例》相關(guān)的同類信息!
  • 本頁收集關(guān)于php封裝的pdo數(shù)據(jù)庫操作工具類與用法示例的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    主站蜘蛛池模板: 镇远县| 平果县| 绥宁县| 南丹县| 湖南省| 雷波县| 蕉岭县| 比如县| 大田县| 乌兰浩特市| 深圳市| 青冈县| 西藏| 贺州市| 宁晋县| 吉首市| 神农架林区| 富锦市| 新郑市| 西安市| 黔西| 广宗县| 台北县| 莱芜市| 衡山县| 固安县| 延川县| 图片| 阜康市| 博罗县| 宽城| 叙永县| 彭泽县| 济源市| 平山县| 郴州市| 蓬溪县| 西平县| 蒲江县| 平利县| 罗平县|