mysql工具类

  1. <?php   
  2. /**  
  3. +----------------------------------------------------------  
  4.  * Mysql操作类  
  5. +----------------------------------------------------------  
  6.  * 文件名称  Db.class.php  
  7. +----------------------------------------------------------  
  8.  * 文件描述  mysql操作类  
  9. +----------------------------------------------------------  
  10.  */  
  11. class Db{   
  12.     //数据库连接标识   
  13.     protected $link = null;   
  14.     //当前操作的表   
  15.     public $table = '';   
  16.     //查询参数   
  17.     protected $options = array();   
  18.     //当前执行的SQL语句   
  19.     protected $sql = '';   
  20.     //用什么编码传递数据   
  21.     protected $dbCharset = 'utf8';   
  22.   
  23.     //缓存路径   
  24.     protected $cachePath = './cache/';   
  25.     //缓存扩展名   
  26.     protected $cacheFileExt = "php";   
  27.     //缓存文件名   
  28.     protected $cacheFileName;   
  29.     //是否缓存   
  30.     protected $cache = false;   
  31.     //缓存更新时间秒数   
  32.     protected $cacheLimitTime = 60;   
  33.   
  34.     //数据返回类型, 1代表数组, 2代表对象   
  35.     protected $returnType = 1;   
  36.   
  37.   /*  
  38.    * 根据当前动态文件生成缓存文件名  
  39.    */  
  40.     function setCacheFileName($fileName) {   
  41.         $cacheFileName = $this->cachePath . strtoupper(md5($fileName)).".".$this->cacheFileExt;   
  42.         $this->cacheFileName=$cacheFileName;   
  43.     }   
  44.   /*  
  45.    * 根据当前动态文件生成缓存文件名  
  46.    */  
  47.     function getCacheFileName() {   
  48.         return  $this->cacheFileName;   
  49.     }   
  50.     /**  
  51.      * 连接数据库  
  52.      *  
  53.      * @access      public  
  54.      * @param       array    $db  数据库配置  
  55.      * @return      resource 数据库连接标识  
  56.      */  
  57.     public function connect($db){   
  58.         //根据配置使用不同函数连接数据库   
  59.         $db['host'] = isset($db['port']) ? $db['host'].':'.$db['port']: $db['host'];   
  60.         $db['char'] = isset($db['char']) ? $db['char']: $this->dbCharset;   
  61.         $func = $db['pconnect'] ? 'mysql_pconnect' : 'mysql_connect';   
  62.         $this->link = $func($db['host'], $db['user'], $db['pwd']);   
  63.         mysql_select_db($db['database'], $this->link);   
  64.         mysql_query("SET NAMES '{$db['char']}'");   
  65.         $this->cachePath = isset($db['cachepath']) ? $db['cachepath']: $this->cachePath;   
  66.         return $this->link;   
  67.     }   
  68.     /**  
  69.      * 查询符合条件的一条记录  
  70.      *  
  71.      * @access      public  
  72.      * @param       string    $where  查询条件  
  73.      * @param       string    $field  查询字段  
  74.      * @param       string    $table  表  
  75.      * @return      mixed             符合条件的记录  
  76.      */  
  77.     public function find($where = NULL, $field = '*'$table = ''){   
  78.         return $this->findAll($where = NULL, $field = '*'$table = '', FALSE);   
  79.     }   
  80.     /**  
  81.      * 查询符合条件的所有记录  
  82.      *  
  83.      * @access      public  
  84.      * @param       string    $where  查询条件  
  85.      * @param       string    $field  查询字段  
  86.      * @param       string    $table  表  
  87.      * @return      mixed             符合条件的记录  
  88.      */  
  89.     public function findAll($where = NULL, $field = '*'$table = ''$all = TRUE){   
  90.         $this->options['where'] = is_null($where) ? @$this->options['where']: $where;   
  91.         $this->options['field'] = isset($this->options['field']) ? $this->options['field']: $field;   
  92.         $this->options['table'] = $table == '' ? $this->table: $table;   
  93.         $sql = "SELECT {$this->options['field']} FROM `{$this->options['table']}` ";   
  94.         $sql .= isset($this->options['join']) ? ' LEFT JOIN '.$this->options['join']: '';   
  95.         $sql .= isset($this->options['where']) ? ' WHERE '.$this->options['where']: '';   
  96.         $sql .= isset($this->options['group']) ? ' GROUP BY '.$this->options['group']: '';   
  97.         $sql .= isset($this->options['having']) ? ' HAVING '.$this->options['having']: '';   
  98.         $sql .= isset($this->options['order']) ? ' ORDER BY '.$this->options['order']: '';   
  99.         $sql .= isset($this->options['limit']) ? ' LIMIT '.$this->options['limit']: '';   
  100.         $this->sql = $sql;   
  101.         $row = NULL;   
  102.         //如果开启了缓存, 那么重缓存中获取数据   
  103.         if ($this->cache === TRUE){   
  104.             $this->setCacheFileName($this->sql);   
  105.             $row = $this->readCache();   
  106.         }   
  107.         //如果读取失败, 或则没有开启缓存   
  108.         if (is_null($row)){   
  109.             $result = $this->query();   
  110.             $row = $all === TRUE ? $this->fetchAll($result): $this->fetch($result);   
  111.             //如果开启了缓存, 那么就写入   
  112.             if ($this->cache === TRUE){   
  113.                 $this->writeCache($row);   
  114.             }   
  115.             $this->options = array();   
  116.         }   
  117.         return $row;   
  118.     }   
  119.     /**  
  120.      * 读取结果集中的所有记录到数组中  
  121.      *  
  122.      * @access public  
  123.      * @param  resource  $result  结果集  
  124.      * @return array  
  125.      */  
  126.     public function fetchAll($result = NULL){   
  127.         $rows = array();   
  128.         while ($row = $this->fetch($result)){   
  129.             $rows[] = $row;   
  130.         }   
  131.         return $rows;   
  132.     }   
  133.     /**  
  134.      * 读取结果集中的一行记录到数组中  
  135.      *  
  136.      * @access public  
  137.      * @param  resource  $result  结果集  
  138.      * @param  int       $type    返回类型, 1为数组, 2为对象  
  139.      * @return mixed              根据返回类型返回  
  140.      */  
  141.     public function fetch($result = NULL, $type = NULL){   
  142.         $result = is_null($result) ? $this->result: $result;   
  143.         $type = is_null($type) ? $this->returnType: $type;   
  144.         $func = $type === 1 ? 'mysql_fetch_assoc' : 'mysql_fetch_object';   
  145.         return $func($result);   
  146.     }   
  147.     /**  
  148.      * 执行SQL命令  
  149.      *  
  150.      * @access      public  
  151.      * @param       string    $sql    SQL命令  
  152.      * @param       resource  $link   数据库连接标识  
  153.      * @return      mixed             数据库结果集  
  154.      */  
  155.     public function query($sql = ''$link = NULL){   
  156.         $sql = emptyempty($sql) ? $this->sql: $sql;   
  157.         $link = is_null($link) ? $this->link: $link;   
  158.         $this->result = mysql_query($sql$link);   
  159.         if (is_resource($this->result)){   
  160.             return $this->result;   
  161.         }   
  162.         //如果执行SQL出现错误, 那么抛出异常   
  163.         exit('<strong>Mysql error:</strong>'.$this->getError());   
  164.     }   
  165.     /**  
  166.      * 执行SQL命令  
  167.      *  
  168.      * @access      public  
  169.      * @param       string    $sql    SQL命令  
  170.      * @param       resource  $link   数据库连接标识  
  171.      * @return      bool              是否执行成功  
  172.      */  
  173.     public function execute($sql = ''$link = NULL){   
  174.         $sql = emptyempty($sql) ? $this->sql: $sql;   
  175.         $link = is_null($link) ? $this->link: $link;   
  176.         if (mysql_query($sql$link)){   
  177.             return TRUE;   
  178.         }   
  179.         return FALSE;   
  180.     }   
  181.     /**  
  182.      * 插入记录  
  183.      *  
  184.      * @access public  
  185.      * @param  array  $data  插入的记录, 格式:array('字段名'=>'值', '字段名'=>'值');  
  186.      * @param  string $table 表名  
  187.      * @return bool          当前记录id  
  188.      */  
  189.     public function add($data$table = NULL){   
  190.         $table = is_null($table) ? $this->table: $table;   
  191.         $sql = "INSERT INTO `{$table}`";   
  192.         $fields = $values = array();   
  193.         $field = $value = '';   
  194.         //遍历记录, 格式化字段名称与值   
  195.         foreach($data as $key => $val){   
  196.             $fields[] = "`{$table}`.`{$key}`";   
  197.             $values[] = is_numeric($val) ? $val : "'{$val}'";   
  198.         }   
  199.         $field = join(','$fields);   
  200.         $value = join(','$values);   
  201.         unset($fields$values);   
  202.         $sql .= "({$field}) VALUES({$value})";   
  203.         $this->sql = $sql;   
  204.         $this->execute();   
  205.         return $this->insertId();   
  206.     }   
  207.     /**  
  208.      * 删除记录  
  209.      *  
  210.      * @access public  
  211.      * @param  string  $where  条件  
  212.      * @param  string  $table  表名  
  213.      * @return bool            影响行数  
  214.      */  
  215.     public function delete($where = NULL, $table = NULL){   
  216.         $table = is_null($table) ? $this->table: $table;   
  217.         $where = is_null($where) ? @$this->options['where']: $where;   
  218.         $sql = "DELETE FROM `{$table}` WHERE {$where}";   
  219.         $this->sql = $sql;   
  220.         $this->execute();   
  221.         return $this->affectedRows();   
  222.     }   
  223.     /**  
  224.      * 更新记录  
  225.      *  
  226.      * @access public  
  227.      * @param  array   $data   更新的数据 格式:array('字段名' => 值);  
  228.      * @param  string  $where  更新条件  
  229.      * @param  string  $table  表名  
  230.      * @return bool            影响多少条信息  
  231.      */  
  232.     public function update($data$where = NULL, $table = NULL){   
  233.         $table = is_null($table) ? $this->table: $table;   
  234.         $where = is_null($where) ? @$this->options['where']: $where;   
  235.         $sql = "UPDATE `{$table}` SET ";   
  236.         $values = array();   
  237.         foreach($data as $key => $val){   
  238.             $val = is_numeric($val) ? $val : "'{$val}'";   
  239.             $values[] = "`{$table}`.`{$key}` = {$val}";   
  240.         }   
  241.         $value = join(','$values);   
  242.         $this->sql = $sql.$value." WHERE {$where}";   
  243.         $this->execute();   
  244.         return $this->affectedRows();   
  245.     }   
  246.     /**  
  247.      * 读取缓存  
  248.      *  
  249.      * @access      public  
  250.      * @return      mixed   如果读取成功返回缓存内容, 否则返回NULL  
  251.      */  
  252.     protected function readCache(){   
  253.         $file = $this->getCacheFileName();   
  254.         if (file_exists($file)){   
  255.             //缓存过期   
  256.             if ((filemtime($file) + $this->cacheLimitTime) < time()){   
  257.                 @unlink($file);   
  258.                 return NULL;   
  259.             }   
  260.             if (1 === $this->returnType){   
  261.                 $row = include $file;   
  262.             }   
  263.             else{   
  264.                 $data = file_get_contents($file);   
  265.                 $row = unserialize($data);   
  266.             }   
  267.             return $row;   
  268.         }   
  269.         return NULL;   
  270.     }   
  271.     /**  
  272.      * 写入缓存  
  273.      *  
  274.      * @access      public  
  275.      * @param       mixed   $data   缓存内容  
  276.      * @return      bool            是否写入成功  
  277.      */  
  278.     public function writeCache($data){   
  279.         $file = $this->getCacheFileName();   
  280.         if ($this->makeDir(dirname($file))){   
  281.             if (1 === $this->returnType){   
  282.                 $data = '<?php return '.var_export($data, TRUE).';?>';   
  283.             }else{   
  284.                 $data = serialize($data);   
  285.             }   
  286.         }   
  287.         return file_put_contents($file$data);   
  288.     }   
  289.     /*  
  290.      * 清除缓存文件  
  291.      * string $fileName 指定文件名(含函数)或者all(全部)  
  292.      * 返回:清除成功返回true,反之返回false  
  293.      */  
  294.     function clearCache( $fileName = "all" ) {   
  295.         if$fileName != "all" ) {   
  296.             iffile_exists$fileName ) ) {   
  297.                 return @unlink( $fileName );   
  298.             }else return false;   
  299.         }   
  300.         if ( is_dir$this->cachePath ) ) {   
  301.             if ( $dir = @opendir( $this->cachePath ) ) {   
  302.                 while ( $file = @readdir( $dir ) ) {   
  303.                     $check = is_dir$file );   
  304.                     if ( !$check )   
  305.                     @unlink( $this->cachePath . $file );   
  306.                 }   
  307.                 @closedir$dir );   
  308.                 return true;   
  309.             }else{   
  310.                 return false;   
  311.             }   
  312.         }else{   
  313.           return false;   
  314.         }   
  315.     }   
  316.       /*  
  317.        * 连续建目录  
  318.        * string $dir 目录字符串  
  319.        * int $mode   权限数字  
  320.        * 返回:顺利创建或者全部已建返回true,其它方式返回false  
  321.        */  
  322.     function makeDir( $dir$mode = "0777" ) {   
  323.         if( ! $dir ) return 0;   
  324.         $dir = str_replace"\\", "/", $dir );   
  325.            
  326.         $mdir = "";   
  327.         foreachexplode"/"$dir ) as $val ) {   
  328.             $mdir .= $val."/";   
  329.             if$val == ".." || $val == "." || trim( $val ) == "" ) continue;   
  330.              
  331.             if( ! file_exists$mdir ) ) {   
  332.                 if(!@mkdir$mdir$mode )){   
  333.                     return false;   
  334.                 }   
  335.             }   
  336.         }   
  337.         return true;   
  338.     }   
  339.     //自动加载函数, 实现特殊操作   
  340.     public function __call($func$args)   
  341.     {   
  342.          if(in_array($funcarray('field''join''where'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值