一個簡單的php數據庫連接和文本緩存綜合類

tta 9年前發布 | 863 次閱讀 PHP

[PHP]代碼    

class Db{
    protected $_connect;
    protected $_db = Array();
    protected $_cache = Array();

    public function __construct($args){
        list($this->_db,$this->_cache) = $args;
    }
    protected function connect($db){
        $this->_connect = mysql_connect($db['hostname'],$db['username'],$db['password']);
        mysql_set_charset('UTF8');
        mysql_select_db($db['databasename'],$this->_connect);
    }
    /**
     *作用:獲取表中數據,并將所查詢到的數據格式化返回,返回格式是數組形式!
     *$sql:傳入的待執行的SQL語句,必須而且只能是SELECT
     *
    */
    public function fetch($sql){
        $result = '';
        if(isset($this->_cache['expire'])){
            $name = md5(strtolower(str_replace(' ','',$sql)));
            $dir = substr($name,0,2);
            $dir = $this->_cache['dir'].'/'.$dir;
            !is_dir($dir) && mkdir($dir,0777);
            !is_dir($dir) && mkdir($dir,0777);
            $this->_cache['path'] = $dir.'/'.$name;
            if(is_file($this->_cache['path']) && $this->check_expire()){
                $result = $this->get();
            }
        }
        if($result == ''){
            $data = $this->exec($sql);
            $result = Array();
            while($result[] = mysql_fetch_array($data,MYSQL_ASSOC)){} //去除索引
            mysql_free_result($data);
            array_pop($result);
            isset($this->_cache['expire']) && $this->write($result);
        }
        return $result;
    }
    /**
     *作用:執行所有的SQL語句,但不包括SELECT!
     *$sql:傳入的待執行的SQL語句,不能為SELECT
     *返回值:TRUE OR FALSE
    */
    public function exec($sql){
        if($this->_connect === null) $this->connect($this->_db); //進行數據鏈接
        if( $result = mysql_query($sql, $this->_connect) ){
            return $result;
        }else{
            die("{$sql}<br />執行錯誤: " . mysql_error());
        }
    }
    /**
     *作用:執行數據庫插入語句,只能是INSERT語句!
     *$v:傳入的待執行的條件,是數組格式table代表待執行插入的表,row是字段,value是待插入的值
     *返回值:mysql_insert_id() OR FALSE
    */  
    public function insert($table,$field,$ignore = 0){
        $D = Array('field'=>'','val'=>'');
        foreach($field AS $key => $v){
            $D['field'] .= $key.',';
            $D['val'] .= "'{$this->escape($v)}',";
        }
        $D['field'] = rtrim($D['field'],',');
        $D['val'] = rtrim($D['val'],',');
        $ignore = $ignore > 0 ? 'IGNORE' : '';
        $sql = "INSERT {$ignore} INTO {$this->_db['perfix']}{$table}({$D['field']}) VALUES({$D['val']})";
        if($this->exec($sql)){
            $insert_id = mysql_insert_id();
            return is_numeric($insert_id) ? $insert_id : TRUE;
        }else{
            return FALSE;
        }
    }
    public function update($table,$field){
        $D = Array('where'=>'','str'=>'');
        $index = 0;
        foreach($field AS $key => $v){
            $index == 0 ? $D['where'] = "{$key} = '{$this->escape($v)}'" : $D['str'] .= "{$key} = '{$this->escape($v)}',";
            $index++;
        }
        $D['str'] = rtrim($D['str'],',');
        $sql = "UPDATE {$this->_db['perfix']}{$table} SET {$D['str']} WHERE {$D['where']}";
        return $this->exec($sql);

    }
    public function delete($table,$field){
        $str = '';
        foreach($field AS $key => $v){
            $str = "{$key} = '{$v}'";
        }
        $sql = 'DELETE FROM '.$this->_db['perfix'].$table.' WHERE '.$str.' LIMIT 1';
        return $this->exec($sql);
    }
    public function sum($table,$condition){
        $totle = $this->fetch('SELECT COUNT(*) AS totle FROM '.$this->_db['perfix'].$table.' WHERE '.$condition);
        return $totle[0]['totle'];
    }
    /**
     *作用:對輸入特殊字符進行過濾
     *$v:待傳入檢測的參數
     *返回值:檢測完的參數
     */ 
    public function escape($v){
        return mysql_real_escape_string($v);
    }
    /*
     *作用:進行緩存判斷 
     */
    public function cache($name,$expire=100000000){
        $this->_cache['expire'] = $expire;
        return $this;
    }
    public function check_expire(){
        return (filemtime($this->_cache['path']) + $this->_cache['expire']) > strtotime("now");
    }

    public function write($data){
        $f = fopen($this->_cache['path'], 'w');
        if ($f) {
            flock($f, LOCK_EX);
            fseek($f, 0);
            ftruncate($f, 0);
            $tmp = fwrite($f, serialize($data));
            if (!($tmp === false)) {
                $result = true;
            }
            fclose($f);
        }
        chmod($this->_cache['path'],0777);
    }
    public function get(){
        $f = fopen($this->_cache['path'], 'r'); 
        $data = fread($f,filesize($this->_cache['path']));
        fclose($f);
        return unserialize($data);
    }
    public function delete_dir($dir = ''){
        $dir = empty($dir) ? $this->_cache['dir'] : $dir;
        !is_dir($dir) && exit;
        $d = opendir($dir);
        $i = 0;
        while(($file = readdir($d)) !== false){
            $path = $dir.'/'.$file;
            if($i > 1) is_file($path) ? unlink($path) : $this->delete_dir($path);
            $i++;
        }
        closedir($d);
        rmdir($dir);
    }
    public function __destruct(){
        isset($this->_connect) && mysql_close($this->_connect);
    }   
}
 本文由用戶 tta 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!