自动DB类

用的DB类,主要采用是的PDO的内容,先对PDO中的关于exec与query两个方法进行封装,并统一进行错误处理,启用异常处理模式与默认字符集设置,在子类中设置一个保护属性protected $table = '';
子类中的获取表的方法统一使用$this->getTBName()方法来获取表名
<?php
    header('Content-type:text/html;charset=utf-8');
    class DB{
        //属性
        private $allow = array('mysql','oracle');
        private $type;
        private $host;
        private $port;
        private $user;
        private $pass;
        private $dbname;
        private $prefix;//表前缀
        private $charset;
        private $db;
        //protected $table;
        //private static $mydb;
        private $mesg = array();
        private $fetch_type;//fethc的模式
/*
        public function __construct($arr = array()){
            $this->type = isset($arr['type']) ? $arr['type'] : 'mysql';
            $this->host = isset($arr['host']) ? $arr['host'] : 'localhost';
            $this->port = isset($arr['port']) ? $arr['port'] : '3308';
            $this->user = isset($arr['user']) ? $arr['user'] : 'root';
            $this->pass = isset($arr['pass']) ? $arr['pass'] : 'root';
            $this->dbname = isset($arr['dbname']) ? $arr['dbname'] : 'shop';
            $this->perfix = isset($arr['perfix']) ? $arr['perfix'] : 'sh_';
            $this->charset = isset($arr['charset']) ? $arr['charset'] : 'utf8';
            $this->fetch_type = isset($arr['fetch_type']) ? $arr['fetch_type'] : PDO::FETCH_ASSOC;
            if(!in_array($this->type,$this->allow)){
                $this->mesg['type_err'] = '不支持当前数据库:'.$this->type;
                exit;
            }
            echo $this->port;
            $this->connect();
            $this->setDBAttribute();
            $this->setCharset();
        }

*/
        /**
         * [__construct 构造函数]
         * @param array $arr [传入相关的数据库信息]
         */
        public function __construct($arr = array()){
            $this->type = isset($arr['type']) ? $arr['type'] : $GLOBALS['config']['mysql']['type'] ;
            $this->host = isset($arr['host']) ? $arr['host'] : $GLOBALS['config']['mysql']['host'];
            $this->port = isset($arr['port']) ? $arr['port'] : $GLOBALS['config']['mysql']['port'];
            $this->user = isset($arr['user']) ? $arr['user'] : $GLOBALS['config']['mysql']['user'];
            $this->pass = isset($arr['pass']) ? $arr['pass'] : $GLOBALS['config']['mysql']['pass'];
            $this->dbname = isset($arr['dbname']) ? $arr['dbname'] : $GLOBALS['config']['mysql']['dbname'];
            $this->prefix = isset($arr['prefix']) ? $arr['prefix'] : $GLOBALS['config']['mysql']['prefix'];
            $this->charset = isset($arr['charset']) ? $arr['charset'] : $GLOBALS['config']['mysql']['charset'];
            $this->fetch_type = isset($arr['fetch_type']) ? $arr['fetch_type'] : PDO::FETCH_ASSOC;
            if(!in_array($this->type,$this->allow)){
                $this->mesg['type_err'] = '不支持当前数据库:'.$this->type;
                exit;
            }
            //echo $this->port;
            //连接数据库
            $this->connect();
            //设置PDO的异常模式
            $this->setDBAttribute();
            //设置数据库的字符集
            $this->setCharset();
        }
        /**
         * [connect 数据库连接]
         * @return [no] [没有返回]
         */
        private function connect(){
            try{
                $this->db = new PDO("{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname}","{$this->user}","{$this->pass}");
            }catch(PDOException $e){
                $this->mesg['con_err'] = '出错文件是:'.$e->getFile().',出错行数:'.$e->getLine();
                exit;
            }
        }
        /**
         * [setDBAttribute 设置PDO的异常模式]
         */
        private function setDBAttribute(){
            $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
            $this->db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        }
        /**
         * [myEXEC PDO中的exec方法的封装]
         * @param  [string] $sql [要执行的sql语句]
         * @return [mixed]      [成功返回1失败返回false]
         */
        private function myEXEC($sql){
            //$sql = addslashes($sql);
            try{
                $res = $this->db->exec($sql);
                return $res ? $res :false;
            }catch(PDOException $e){
                $this->mesg['exec_err'] = 'exec操作出错:'.$e->getFile().',出错的位置:'.$e->getLine();
                return false;
            }
        }
        /**
         * [myQuery PDO中的query方法的封装]
         * @param  [string] $sql [要执行的SQL语句]
         * @return [mixed]      [如果成功返回结果集,失败返回false]
         */
        private function myQuery($sql){
            //$sql = addslashes($sql);
            try{
                $stmt = $this->db->query($sql);
                //echo $stmt->rowCount();
                return $stmt->rowCount() ? $stmt :false;
            }catch(PDOException $e){
                $this->mesg['query_err'] = 'query操作出错:'.$e->getFile().',出错的位置:'.$e->getLine();
                return false;
            }
        }
        /**
         * [setCharset 设置数据库的字符集]
         */
        private function setCharset(){
            $sql = "set names {$this->charset}";
            $this->myEXEC($sql);
        }
        /*
        public static function getInstance($arr){
            if(self::$mydb){

            }else{
                return self::$mydb = new DB($arr);
            }
            return self::$mydb;
        }
        */
        /**
         * [db_insert 封装插入方法]
         * @param  [string] $sql [要执行的sql语句]
         * @return [int]      [如果成功返回自增ID,否则返回false]
         */
        public function db_insert($sql){
            return $this->myEXEC($sql) ? $this->db->lastInsertId() : false;
        }
        /**
         * [db_update 封装更新方法]
         * @param  [string] $sql [要执行的sql语句]
         * @return [boolean]      [更新成功返回true,失败返回false]
         */
        public function db_update($sql){
            return $this->myEXEC($sql) ? true : false;
        }
        /**
         * [db_delete 封装删除方法]
         * @param  [string] $sql [要执行的sql语句]
         * @return [boolean]      [更新成功返回true,失败返回false]
         */
        public function db_delete($sql){
            return $this->myEXEC($sql) ? true :false;
        }
        /**
         * [db_getRow 获取一条结果集]
         * @param  [string] $sql [要执行的sql语句]
         * @return [mixed]      [成功返回一个一维数组,失败返回false]
         */
        public function db_getRow($sql){
            //echo $sql;
            $stmt = $this->myQuery($sql);
            //var_dump($stmt);
            return $stmt ? $stmt->fetch($this->fetch_type) : false;
        }
        /**
         * [db_getRows 获取多个结果]
         * @param  [string $sql [要执行的sql语句]
         * @return [mixed]      [成功返回一个二维数组,失败返回false]
         */
        public function db_getRows($sql){
            $stmt = $this->myQuery($sql);
            return $stmt ? $stmt->fetchAll($this->fetch_type) : array();
        }
        protected function getTBName(){
            return $this->prefix.$this->table;
        }
                //__sleep方法
        public function __sleep(){
            //返回需要保存的属性的数组
            return array('host','port','user','pass','dbname','charset','prefix');
        }

        //__wakeup方法
        public function __wakeup(){
            //连接资源
            $this->connect();
            //设置字符集和选中数据库
            $this->setCharset();
        }
        public function getIP(){
            if($_SERVER['REMOTE_ADDR']){
                $ip = $_SERVER['REMOTE_ADDR'];
            }else if(getenv('REMOTE_ADDR')){
                $ip = getenv('REMOTE_ADDR');
            }else{
                $ip = 'Unknown';
            }
            return $ip;
        }
    }
    //$mypdo = DB::getInstance(array('type'=>'mysql','dbname'=>'test'));
    //echo $m
   // echo '<pre>';
    //var_dump($mypdo);
    //var_dump($mypdo->db_getRows("select * from user "));
    //var_dump($mypdo->db_insert("insert into user values(null,'小九',38)"));
    //var_dump($mypdo->db_update("update user set u_name = '康乾7' where u_id = 20"));
    //var_dump($mypdo->db_delete("delete from user where u_id = 20"));
    //$mypdo = new DB();
   // var_dump($mypdo);

 

posted @ 2016-09-12 13:54  青铜到王者  阅读(350)  评论(0编辑  收藏  举报