1. 程式人生 > >較全面的php mysql封裝,使用mysqli物件支援預處理和事務,可輸出執行後的sql

較全面的php mysql封裝,使用mysqli物件支援預處理和事務,可輸出執行後的sql

下篇的文章已經更新咯,使用pdo安全性更高,相容性更強

基於mysqli寫的sql封裝語句,可支援預處理和事務,可以輸出最後執行的sql。

所有的條件以陣列傳遞即為預處理語句,否則為原始語句執行傳遞字串

呼叫方法如下:

$mysqlObj = new mysqliModel();

新增=》
$data['cat_name'] = '測試1111';
$data['spec'] = MD5('描述');
$data['cname'] = '執行三次?'; 
$data['cat_name'] = '修改測試2';
$result = $mysqliObj->add("category",$data);//第一個引數為表名,第二個引數為處理的陣列,若post的陣列都是就是表單資料即可不用傳遞,若部分需要進行加密等操作,只需要將鍵值寫入陣列並賦值處理後的資料

修改=>$result = $mysqliObj->save("category",$id,$data);//和新增方法使用一致,只是傳遞的id為主鍵值

update是基於add和save方法,可以在新增和修改時都使用$result = $mysqliObj->update("category",$data);

刪除=>$result = $mysqliObj->del("category",$id);//主鍵id刪除

$result = $mysqliObj->dels("category",$ids);//根據主鍵批量刪除,返回刪除總數。ids可以是一個數組,也可以是逗號分隔的字串

$result = $mysqliObj->delc("category",$conditon);//根據條件刪除

查詢=>$result = $mysqObj->find("category",$id);//根據主鍵查詢單條記錄

$result = $mysqlObj->select("category");//查詢表中所有值

當需要根據一定條件和排序等等限制條件時可以使用連貫操作如$result = $mysqlIbj->field('id')->where("id= 1")->order("id asc,cid desc")->limit(1,2)->select('category);\

where()中可傳遞陣列,即為預處理

輸出sql語句:echo $mysqlObj->getsql();或者echo $mysqlObj->_sql();

還有很多的的方法比如分頁等等,這裡就不詳述了,可以自行檢視程式碼

<?php 

header("content-type:text/html;charset=utf-8");
/**
 * autor:sujianbin
 * 2016-09-01
 * 採用mysqli物件方式連線
 * MYSQL中只有INNODB和BDB型別的資料表才能支援事務處理!其他的型別是不支援的!(alter table tablename ENGINE = InnoDB)
 * 支援預處理技術,主要在連線和編譯過程精簡,還可以SQL防止注入,快速執行
 */


class mysqliModel{
    private $mysqli = '';//當前mysqli物件
    private $field = '';//需要查詢的欄位
    private $where = '';//查詢條件 
    private $order = '';//排序規則
    private $limit = '';//查詢數量
    private $pri = '';//主鍵
    private $table = '';//表名
    private $params = array();//預處理資料
    private static $host = 'localhost';//主機名或ip地址
    private static $db_user = 'root';//使用者名稱
    private static $db_pass = 'root';//密碼
    private static $db_name = 'mymoban';//資料庫名稱
    private $db_press = 'su_';//資料庫表字首
    private $db_log = false;//是否開啟日誌
    private $auto_commit = TRUE;//是否開啟自動提交,不適用於查詢操作,預設自動提交,如若關閉操作時請先呼叫方法關閉
    private $debug = 1;//是否開啟除錯模式,開啟後出現錯誤查詢會出現自動打印出sql語句


    /**
     * 建構函式
     */
    public function __construct($field='',$where='',$order='',$limit='') {
        $this->field = $field;
        $this->where = $where;
        $this->order = $order;
        $this->limit = $limit;
        $this->mysqli = new mysqli(self::$host,self::$db_user,self::$db_pass,self::$db_name);
        if($this->mysqli->connect_error){
            echo "Failed to connect to MySQL: " . $this->mysqli->connect_error;exit;
        }else{
            $this->mysqli->query("SET names UTF8");
            session_start();
            error_reporting(E_ALL ^ E_NOTICE); 
            date_default_timezone_set("PRC");
        }
    }


    /**
     * __get()方法用來獲取私有屬性
     */
    public function __get($property_name){
     if(isset($this->$property_name)){
       return($this->$property_name);
     }else{
       return null;
     }
    }


    /**
     * __set()方法用來設定私有屬性
     */
    public function __set($property_name,$value){
     $this->$property_name = $value;
    }


    /**
     * 解構函式
     */
    public function __destruct(){
        $this->destroy();
        $this->mysqli->close();
    }


    /**
     * 函式執行錯誤處理
     * @param  string $functionName 函式名稱
     * @param  array  $args         包含資訊的陣列
     * @return 返回執行狀態
     */
    public function __call($functionName,$args){
    if(strstr($functionName,'getFieldBy')){
     $search = str_replace('getFieldBy','',$functionName);
     return $this->getFieldBy($args,$search);
    }else if(!function_exists($functionName)){
        $msg = "你所呼叫的函式: ".$functionName."不存在";
        echo $msg;exit;
        }
    }


    /**
     * 銷燬變數
     * @return 無
     */
    protected function destroy(){
        $this->db_log($this->_sql());
        if($type == 0){
            $array = array('field'=>'','where'=>'','order'=>'','limit'=>'','table'=>'','pri'=>'');
        }
        foreach($array as $key=>$value){
            unset($this->$key);
        }
    }


    
    /**
     * 關閉自動提交事務處理
     * @param  string $auto_commit 是否自動提交
     * @return 返回當前物件
     */
    public function auto_commit($auto_commit = ''){
        $this->auto_commit = $auto_commit?$auto_commit:$this->auto_commit;
        $this->mysqli->autocommit(FALSE);
        return $this;
    }


    /**
     * 事務提交
     * @return boolean 布林型結果
     */
    public function commit(){
    if(!$this->mysqli->error){
    $result = $this->mysqli->commit();
       if($result){
           return true;
       }else{
           return null; 
       }
    }else{
    //事務回滾
    $this->mysqli->rollback();
          return null;
    }
    }


    /**
     * 給表加上字首
     * @param  string $table 表名
     * @return string 返回完整等我表名
     */
    protected function db_press($table){
        return "`".$this->db_press.$table."`";
    }


    /**
     * 獲取毫秒技術
     * @param  string $format     [description]
     * @param  [type] $utimestamp [description]
     * @return [type]             [description]
     */
    private function udate($format = 'u', $utimestamp = null) {
        if (is_null($utimestamp))
            $utimestamp = microtime(true);
        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);
        return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
    }


    /**
     * 寫入日誌
     * @param  string $sql 執行的sql語句
     * @return 無
     */
     private function db_log($sql){
      if($this->db_log){
        $file = 'cache/log.txt';
          if(!file_exists($file)){
            $myfile = fopen($file, "w");
          }
          $filesize = filesize($file)/1024/1024;//1M
          if($filesize > 1){
              file_put_contents($file,"");//防止日誌太大
          }
       if(stripos("insert",'@'.$sql) || stripos("update",'@'.$sql)){
           file_put_contents($file,$this->udate('Y-m-d H:i:s.u')."  ".$sql."\r\n\r\n",FILE_APPEND | LOCK_EX);
       }
      }
    }


    /**
     * 過濾字元
     * @param  string $item 需要過濾的字元
     * @return string  返回過濾後的字元
     */
    private function saddslashes($item){
      $item=trim($item);
      if(!get_magic_quotes_gpc()) $item = addslashes($item);
      return $item;
    }    


    /**
     * 獲取最後執行的sql語句
     * @return string 返回執行的sql語句
     */
    public function getsql(){
        if(is_array($this->params)){
            foreach($this->params as $k=>$v){
                if($k != 0){
                    if(strpos($this->sqlx,'?')){
                        $sql = substr($this->sqlx,0,strpos($this->sqlx,'?')+1);
                        if(strpos($sql,'like ?')){
                            $this->sqlx = preg_replace("/\?/","'".$v."'",$this->sqlx,1);
                        }else{
                            $this->sqlx = preg_replace("/\?/",$v,$this->sqlx,1);
                        } 
                    }
                    //$this->sqlx = preg_replace("/like \?/","like '".$v."'",$this->sqlx,1);
                    //$this->sqlx = preg_replace("/\?/",$v,$this->sqlx,1);
                }
            }
        }
      return $this->sqlx;
    }


    /**
     * getsql函式的別名
     * @return string 返回sql語句
     */
    public function _sql(){
    return $this->getsql();
    }


    
    /**
     * 自定義sql語句執行
     * @param  string $com_sql 需要執行的語句
     * @return 未開啟事務時才有返回
     */
    public function querySql($com_sql){
        $results = $this->mysqli->query($com_sql);
        $this->sqlx = $com_sql;
        $this->destroy();
        if($this->auto_commit != FALSE){
          return $results;
        }
    }


    /**
      *公共函式獲取表資訊
      *@param string $table 表名
      *@param array $array 對提交的所有資料進行過濾
      */
    private function common($table,$array=''){
        $this->params = '';
      $this->table = $this->db_press($table);
      $query = $this->mysqli->query("DESC {$this->table}");
      while($row = $query->fetch_array()){
        $result[] = $row['Field'];
        if($row['Key'] == 'PRI'){
          $zhujian = $row['Field'];
        }
      }
      $arr = $left = $right = '';
      //獲取前臺處理後的陣列
      if(empty($array)){
        $data = count($_POST) != 0 ? $_POST:'';
      }else{
         $data = count($_POST) != 0 ? $array + $_POST : $array;
      }
      $sqlR = '';
        if(is_array($data)){
            foreach ($data as $key => $value) { 
                //過濾欄位處理
                if(in_array($key,$result)){
                  //為欄位加上`符號和過濾欄位
                  $value = $this->saddslashes($value);
                  $left =$left. '`'.$key.'`'.',';
                  //$right =$right.$value.'+-+_=_';(廢除字串形式,易導致bug)
                  $right[] = $value;
                  $arr=$arr."`".$key."`=?".',';//專為修改設定
                  $sqlR .= '?,';//專為新增設定
                }
            }
        }
     
      $sqlR = substr($sqlR,0,-1);
      $left = substr($left,0,-1);
      //$right = substr($right,0,-1);
      $sql = substr($arr,0,-1);
      $temp['left'] = $left;
      $temp['right'] = $right;
      $temp['sql'] = $sql;
      $temp['zhujian'] = $zhujian;
      $temp['sqlR'] = $sqlR;
      return $temp;
    }


    /**
      * 需要查詢的欄位
      * @param  string $field 查詢的欄位
      * @return $this 返回當前物件
      */
    public function field($field){
        if(!empty($field)){
            if(strpos($field,',') && !strpos($field,'.')){
                $field = explode(',',$field);
                foreach ($field as $key => $value) {
                    $field[$key] = '`'.$value.'`'; 
                }
                $this->field = implode(',',$field);
            }else if(strpos($field,'.')){
                $this->field = $field;
            }else{
                $this->field = '`'.$field.'`';
            }
        }else{
            $this->field = '*';
        }
        return $this;
    }


    /**
      * 排序條件
      * @param  string $order 排序條件
      * @return $this 返回當前物件
      */
    public function order($order){
        $this->order = $order?'ORDER BY '.$order :'';
        return $this;
    }


    /**
      * 查詢數量
      * @param  int $offset 開始位置
      * @param  int $length 查詢長度
      * @return $this 返回當前物件 
      */
    public function limit($offset,$length){
        $this->limit = $length?('LIMIT '.$offset.','.$length) :'';
        return $this;
    }


    /**
      * 查詢條件
      * @param  array|string $condition 查詢條件
      * @return $this 返回當前物件 
      */
    public function where($condition=''){
        $this->params = '';
        if(!empty($condition)){
            if(is_array($condition)){
                $conditions = $this->condition($condition);
                $this->where = $conditions['right'];
                $this->where = $this->where?'and '.$this->where:'';
                $this->params = $conditions['params'];
            }else{
                $this->where = 'and '.$condition;
            }
        }
        return $this;
    }


    /**
     * 解析條件陣列
     * @param  array $condition 條件陣列
     * @return array 返回陣列,包含右側prepare語句和param陣列
     */
    public function condition($condition){
        $right = '';
        if(is_array($condition)){
            foreach($condition as $k=>$v){
                if(is_array($v)){
                    if(empty($v['description'])){
                        $right.="and `".$k."` ".$v['terms']." ? ";
                        $params[] = $v['value'];
                    }else{
                        if(is_array($v['value'])){
                            $right.='and (';
                            foreach($v['value'] as $k1=>$v1){
                                $params[] = $v1;
                                if(count($v['value']) != $k1+1){
                                    $right.= "`".$k."` ".$v['terms'].' ? '.$v['description']." ";   
                                }else{
                                    $right.= "`".$k."` ".$v['terms'].' ?';  
                                }
                            }
                            $right.=') ';
                        }else{
                            $right.=$v['description']." `".$k."` ".$v['terms']." ? ";
                            $params[] = $v['value'];
                        }
                    }
                }else{
                    $right.="and `".$k."`".'=? ';
                    $params[] = $v;
                }
            }
            $right = preg_replace('/and /', '', $right, 1); //只替換一次(去掉第一次出現的字元and )  
        }
        $condition['right'] = &$right;
        $condition['params'] = &$params;
        return $condition;
    }


    /**
      * 獲取引數型別
      * @param  array $param 當前陣列
      * @param  int 主鍵id
      * @param  int $type 0表示主鍵放在最後,1表示主鍵放在最前
      * @return string  返回型別長字串  
      */
    protected function paramType($param,$id,$type=0){
    $arr = '';
        if($type ==1 && $id){
            $arr.='i';
        }
        if(is_array($param)){
            foreach($param as $k=>$v){
                if (ctype_digit((string)$v)){
                        $arr.= ($v <= PHP_INT_MAX) ? 'i' : 's';
                }else if (is_numeric($v)){
                    $arr = $arr.'d';
                }else{
                    $arr .='s'; 
                }   
            }   
        }
        if($type ==0 && $id){
            $arr.='i';
        }
   return $arr;
}


    /**
      * 預處理引用引數
      * @param  string|array $params 需要處理的字串
      * @param  int    $id 主鍵
      * @param  int type 0表示主鍵放在最後,1表示主鍵放在最前
      * @return array  返回魔術方法陣列 
      */
    protected function bindParam($params,$id='',$type=0){
        if($params){
            if(is_array($params)){
                $arrays[] = &$this->paramType($params,$id,$type);
                if($type ==1  && $id){
                    $arrays[] = &$id; 
                } 
                foreach($params as $k=>$v){
                    $arrays[] = &$params[$k]; //注意此處的引用
                }     
            }
            // else{
            //     $params = explode('+-+_=_',$params);//傳入字元含有相同的符號會導致準備語句出錯,因此廢除當前操作
            //     $arrays[] = &$this->paramType($params,$id,$type);
            //     if($type ==1  && $id){
            //         $arrays[] = &$id; 
            //     } 
            //     foreach($params as $k=>$v){
            //         $arrays[] = &$params[$k];
            //     }    
            // }
        }else{
            $arrays[] = &$this->paramType($params,$id,$type);
            if($type ==1  && $id){
                $arrays[] = &$id; 
            }
        }
        if($type ==0  && $id){
            $arrays[] = &$id; 
        }
        return $arrays;
    }


    /**
      * 新增單條資料
      * @param  string $table  表名
      * @param  array  $data   需要改變的陣列引數值
      * @return 返回執行結果
      */
    public function add($table,$data=''){
      $temp = $this->common($table,$data);
      $left = $temp['left'];
      $sqlR = $temp['sqlR'];
      $this->sqlx = "INSERT INTO {$this->table} ($left) VALUES ($sqlR)";
        $stmt = $this->mysqli->stmt_init;
      $stmt = $this->mysqli->prepare($this->sqlx);
      $params = $temp['right'];
        $this->params = $this->bindParam($params);
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params));// 魔術方法直接call
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $results = $stmt->execute();
        $this->destroy();
        if($this->auto_commit != FALSE){
            if($stmt->affected_rows){
                return $results;
            }else{
                return null; 
            }
        }
    }


    /**
      * 修改單條資料
      * @param  string $table  表名
      * @param  int    $id     主鍵id 
      * @param  array  $data   需要改變的陣列引數值
      * @return 返回執行結果
      */
    public function save($table,$id,$data=''){
        $temp = $this->common($table,$data);
        $sql = $temp['sql'];
        $zhujian = $temp['zhujian'];
        $params = $temp['right'];
        $id = (int)$id;
        $this->sqlx = "UPDATE {$this->table} SET $sql WHERE `{$zhujian}` = ?";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        $this->params = $this->bindParam($params,"$id");
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params,"$id"));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $results = $stmt->execute();
        $this->destroy();
        if($this->auto_commit != FALSE){
            if($results){
                return $results;
            }else{
                return null; 
            }
        }
    }


    /**
      * 基於add、save方法後,新增和修改可統一使用update
      * @param  string $table 表名
      * @param  array $data 傳值處理陣列
      * @return 返回執行結果
      */
    public function update($table,$data){
        $temp = $this->common($table,$data);
        $zhujian = $temp['zhujian'];
        if(empty($_POST[$zhujian])){//add
            return $this->add($table,$data);
        }else{
            $id = $_POST[$zhujian];
            return $this->save($table,$id,$data);
        }
    }


    /**
      * 根據主鍵刪除單表的資料
      * @param  string  $table 表名
      * @param  int     $id    主鍵id
      * @return string  返回結果
      */
    public function del($table,$id){
        $temp = $this->common($table);
        $zhujian = $temp['zhujian'];
        $this->sqlx = "DELETE FROM {$this->table}  WHERE   `{$zhujian}` = ?";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        $this->params = $this->bindParam($params='',"$id");
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params='',"$id"));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $results = $stmt->execute();
        $this->destroy();
        if($this->auto_commit != FALSE){
            if($stmt->affected_rows){
                return $results;
            }else{
                return null; 
            }
        }
    }


    /**
     * 根據所傳主鍵批量刪除資料
     * @param  string $table 表名
     * @param  string|array  $ids   主鍵組成的字串(必須以逗號隔開)或者陣列
     * @return int 返回刪除總數   
     */
    public function dels($table,$ids){
        $temp = $this->common($table);
        $zhujian = $temp['zhujian'];
        $right = '';
        if(is_array($ids)){
            $params = $ids;
            foreach($ids as $k=>$v){
                if($k == 0){
                    $right.='?';
                }else{
                    $right.=',?';
                }
            }   
        }else{
            $params = explode(',',$ids);
            foreach($params as $k=>$v){
                if($k == 0){
                    $right.='?';
                }else{
                    $right.=',?';
                }    
            }
        }
        $this->sqlx = "DELETE FROM {$this->table}  WHERE `{$zhujian}` IN ($right)";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        $this->params = $this->bindParam($params);
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $results = $stmt->execute();
        $this->destroy();
        if($this->auto_commit != FALSE){
            if($stmt->affected_rows){
                return $stmt->affected_rows;
            }else{
                return null; 
            }
        }
    }


    /**
     * 根據條件刪除資料
     * @param  string $table     表名
     * @param  array  $condition 條件
     * @return int 返回刪除總數
     */
    public function delc($table,$condition){
        $this->table = $this->db_press($table);
        $conditions = $this->condition($condition);
        $right = $conditions['right'];
        $params = $conditions['params'];
        $this->sqlx = "DELETE FROM {$this->table} WHERE $right";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        $this->params = $this->bindParam($params);
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $results = $stmt->execute();
        $this->destroy();
        if($this->auto_commit != FALSE){
            if($stmt->affected_rows){
                return $stmt->affected_rows;
            }else{
                return null; 
            }
        }
    }


    /**
      * 獲取表的表名或者單表時的主鍵和欄位
      * @param  string $table 表名集合
      * @return 無返回,已將值設定為類變數
      */
    public function getTable($table){
        if(!strpos($table,',')){//單表查詢主鍵
            $this->table = $this->db_press($table);
            $query = $this->mysqli->query("DESC {$this->table}");
            while($row =$query->fetch_array(MYSQLI_ASSOC)){
                $result[] = $row['Field'];
                if($row['Key'] == 'PRI'){
                    $this->pri = $row['Field'];
                }
            }
        }else{
            $table = explode(',',$table);
            foreach ($table as $key => $value) {
                $table[$key] = $this->db_press($value); 
            }
            $this->table = implode(',',$table);
        }
    } 


    /**
     * 根據主鍵查詢單條記錄
     * @param  string $table 表名
     * @param  int $id    主鍵
     * @return array/string   成功返回當條記錄失敗返回null
     */
    public function find($table,$id){
        $id = (int)$id;
        $this->getTable($table);
        $this->field = ($this->field)?($this->field) :'*';
        $this->sqlx = "SELECT {$this->field} FROM {$this->table} WHERE `{$this->pri}` = ? {$this->where} {$this->order} {$this->limit}";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        if(!$this->where)
            $this->params = '';
        $params = $this->params;
        //var_dump($params);
        $this->params = $this->bindParam($params,$id,1);
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params,$id,1));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $results =$result->fetch_assoc();
        $result->close();//釋放結果集
        $this->destroy();
        if($results){
            return $results;
        }else{
            return null; 
        }
    }


    /**
      * 查詢符合條件的所有資料
      * @param  string $table 表名
      * @return array/string   成功返回滿足條件的所有記錄失敗返回null
      */
    public function select($table){
        $this->getTable($table);
        $this->field = ($this->field)?($this->field) :'*';
        $this->sqlx = "SELECT {$this->field} FROM {$this->table} WHERE 1 {$this->where} {$this->order} {$this->limit}";
        if(!$this->where)
            $this->params = '';
        if($this->params){
            $stmt = $this->mysqli->stmt_init;
            $stmt = $this->mysqli->prepare($this->sqlx);
            $params = $this->params;
            $this->params = $this->bindParam($params);
            $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params));
            if(!$re and $this->debug){
                exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
            }
            $stmt->execute();
            $result = $stmt->get_result(); 
        }else{
            $result = $this->mysqli->query($this->sqlx); 
            if(!$result and $this->debug){
                exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
            }
        }
        while($row = $result->fetch_array(MYSQLI_ASSOC)){
            $results[] = $row;
        }
        $result->close();
        $this->destroy();
        if($results){
            return $results;
        }else{
            return null; 
        }
    }


    /**
      * 根據主鍵設定某個欄位的值
      * @param string $table  表名
      * @param int $id     主鍵
      * @param string $field_name  欄位名
      * @param string $field_value 欄位值
      */
    public function setField($table,$id,$field_name,$field_value){
        $this->getTable($table);
        $this->sqlx = "UPDATE {$this->table} SET `{$field_name}` = ? WHERE `{$this->pri}` = ?";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        $params[] = $field_value;
        $params[] = (int)$id;
        $this->params = $this->bindParam($params);
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $results = $stmt->execute();
        $this->destroy();
        if($this->auto_commit != FALSE){
            if(!$results){
                return null;
            }else{
                return true;
            }
        }
    }


    /**
      * 根據查詢欄位返回需要的欄位
      * @param  檢視_call()方法呼叫  $args   
      * @param  檢視_call()方法呼叫  $search
      * @param  string $field_c 條件欄位
      * @param  string $field_f 需要查詢欄位
      * @return 返回需要查詢的欄位值
      */
    public function getFieldBy($args,$search){
        $field_c = $search;
        $this->table = $args[0];
        $this->table = $this->db_press($this->table);
        $where = "`{$field_c}` = ?";//
        $field_f = $args[2];
        $this->sqlx = "SELECT `{$field_f}` FROM {$this->table} WHERE {$where}";
        $stmt = $this->mysqli->stmt_init;
        $stmt = $this->mysqli->prepare($this->sqlx);
        $this->params = $this->bindParam($params,$args[1]);
        $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params,$args[1]));
        if(!$re and $this->debug){
            exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
        }
        $stmt->execute();
        $result = $stmt->get_result();
        $results = $result->fetch_assoc();
        $this->destroy();
        if(!$results){
            return null;
        }else{
            return $results[$field_f];
        }
    }


    /**
      * 將資料自動加上對應資料
      * @param string $table 表名
      * @param int $id 主鍵 
      * @param string $field 欄位名
      * @param int $num   增加數量
      */
    public function setInc($table,$id,$field,$num){
        $this->getTable($table);
        $method = getFieldBy.$this->pri; 
        $fields = $this->$method($table,$id,$field);
        $fields+=$num;
        $results = $this->setField($table,$id,$field,$fields);
        if($this->auto_commit != FALSE){
            if($results){
                return $results;
            }else{
                return null;
            }
        }
    }


    /**
      * 將資料自動減去對應資料最低值為0
      * @param string $table 表名
      * @param int $id 主鍵 
      * @param string $field 欄位名
      * @param int $num   減去數量
      */
    public function setDec($table,$id,$field,$num){
        $this->getTable($table);
        $method = getFieldBy.$this->pri; 
        $fields = $this->$method($table,$id,$field);
        $fields-=$num;
        if($fields < 0){
            $fields = 0;
        }
        $results = $this->setField($table,$id,$field,$fields);
        if($this->auto_commit != FALSE){
            if($results){
                return $results;
            }else{
                return null;
            }
        }  
    }


    /**
      * 查詢滿足條件的總數
      * @param  string table表名
      * @param  string field欄位名
      * @return 返回滿足條件的數量
     */
    public function count($table,$field=''){
        if(strpos($table,',')){
            $table = $this->db_press($table);
        }else{
            $table = explode(',',$table);
            foreach ($table as $key => $value) {
                $value = $this->db_press($value);
                $table[$key] = $value; 
            }
            $table = implode(',',$table); 
        }
        $this->field = $field?"count($field) as counts":"count(*) as counts";
        if(!$this->where)
            $this->params = '';
        $this->sqlx = "SELECT {$this->field} FROM {$table} WHERE 1 {$this->where} {$this->order} {$this->limit}";
        if($this->params){
            $stmt = $this->mysqli->stmt_init;
            $stmt = $this->mysqli->prepare($this->sqlx);
            $params = $this->params;
            $this->params = $this->bindParam($params);
            $re = call_user_func_array(array($stmt,'bind_param'),$this->bindParam($params));
            if(!$re and $this->debug){
                exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
            }
            $stmt->execute();
            $result = $stmt->get_result(); 
        }else{
            $result = $this->mysqli->query($this->sqlx); 
            if(!$result and $this->debug){
                exit("親,遇到問題咯,當前sql語句為:".$this->_sql());
            }
        }
        $results = $result->fetch_assoc();
        $counts = $results["counts"];
        $result->close();
        $this->destroy();
        return $counts?$counts:0;
    }


    /**
       * 查詢分頁方法
       * @param  string  $table      表名
       * @param  string  $page       當前頁碼
       * @param  string  $num        預設顯示頁數10
       * @param  string  $num_page   預設分頁數8
       * @param  string  $fields     需要查詢的欄位
       * @param  string  $order      排序條件
       * @param  string $first    第一頁(根據需要傳入)
       * @param  string $pre      上一頁(根據需要傳入)
       * @param  string $next     下一頁(根據需要傳入)
       * @param  string $end      尾頁(根據需要傳入)
       * @return array    成功返回陣列$list['list']為查詢資料$list['page_show']為分頁樣式           
     */
    public function search($table,$page = '',$num = '',$num_page = '',$first = '第一頁',$pre= '上一頁',$next = '下一頁',$end = '尾頁'){
        //每頁顯示數量
        $_pageNum = $num ? $num : 10;
        $start = ceil(($page-1)*$_pageNum);
        //將值賦給變數否則會被銷燬
        $where1 = $this->where;
        $order1 = $this->order;
        $field1 = $this->field;
        $params = $this->params;
        $results = $this->count($table);
        //獲取查詢的總數
        $counts = count($results);
        //將變數再賦值給類變數,完成查詢
        $this->where = $where1;
        $this->order = $order1;
        $this->field = $field1;
        $this->limit = " LIMIT $start,$_pageNum";
        $this->params = $params;
        $list = $this->select($table);
        $this->destroy();
        if($counts != 0){
            //賦值資料結果集
            $list['list'] = $list;
            //預設分頁顯示數8
            $num_page = $num_page ? $num_page : 8;
            //賦值分頁結果集
            $list['page_show'] = $this->page($page,$counts,$num,$num_page,$first,$pre,$next,$end);
            //賦值查詢的總數
            $list['counts'] = $counts;
            return $list;
        }else{
            return null;
        }
    }


     /**
     * 根據結果集陣列進行分頁
       * @param  array $array    結果集資料
       * @param  int $page     當前頁碼
       * @param  string  $page       當前頁碼
       * @param  string  $num        預設顯示頁數10
       * @param  string  $num_page   預設分頁數8
       * @param  string $first    第一頁(根據需要傳入)
       * @param  string $pre      上一頁(根據需要傳入)
       * @param  string $next     下一頁(根據需要傳入)
       * @param  string $end      尾頁(根據需要傳入)
       * @return array    成功返回陣列$list['list']為查詢資料$list['page_show']為分頁樣式 $list['counts']為總數  
     */
    public function getPage($array,$page,$num='',$num_page='',$first='第一頁',$pre='上一頁',$next='下一頁',$ends='尾頁'){
        if(!empty($array)){
            $counts = count($array);
            $_pageNum = $num ? $num : 10;
            $start = ceil(($page-1)*$_pageNum);
            $end = $start + $_pageNum;
            if($counts>0){
                foreach ($array as $key=>$v){
                    if($key>=$start && $key<$end){
                        $list[] = $v;
                    }
                }
            }
            $lists['list'] = $list;
            $num_page = $num_page ? $num_page : 8;
            $lists['page_show'] = $this->page($page,$counts,$num,$num_page,$first,$pre,$next,$ends);
            $lists['counts'] = $counts;
            return $lists;
        }else{
            return null;
        }
    }


    /**
       * 分頁方法
       * @param  int $page     當前頁碼
       * @param  int $counts   總數
       * @param  integer $num 每頁顯示數(預設10條)
       * @param  integer $num_page 預設分頁數(預設8條)
       * @param  string $first    第一頁(根據需要傳入)
       * @param  string $pre      上一頁(根據需要傳入)
       * @param  string $next     下一頁(根據需要傳入)
       * @param  string $end      尾頁(根據需要傳入)
     */
    public function page($page,$counts,$num='',$num_page='',$first = '',$pre='',$next='',$end=''){
        //獲取當前url使得查詢去除分頁影響
        $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'];
        $url1 = strpos($url,"&page");
        if(!empty($url1)){
          $url = substr($url,0,$url1);
        }else{
          $url = $url;
        }
        //分頁顯示樣式處理
        //第一頁
        $first = $first ? $first : '';
        //上一頁
        $pre = $pre ? $pre : '«';
        //下一頁
        $next = $next ? $next : '»';
        //最後一頁
        $end = $end ? $end : '';
        //分頁結果處理
        //預設顯示數量為10
        $_pageNum = $num ? $num : 10;
        //預設分頁顯示數8
        $num_page = $num_page ? $num_page : 8;  
        //總頁數
        $pages = ceil($counts/$_pageNum);
        //當前頁面小於1 則為1
        $page = $page<1?1:$page;
        //當前頁大於總頁數 則為總頁數
        $page = $page > $pages ? $pages : $page;
        //頁數小當前頁 則為當前頁
        $pages = $pages < $page ? $page : $pages;
        //計算開始頁
        //計算基數
        $_start = 1 + floor(($page-1)/$num_page)*$num_page;
        $_start = $_start<1 ? 1 : $_start;
        //計算結束頁
        $_end = $_start + $num_page;
        $_end = $_end>$pages? $pages : $_end;
        //當前顯示的頁碼個數不夠最大頁碼數,在進行左右調整
        $_curPageNum = $_end-$_start+1;
        //左調整
        if($_curPageNum<$_pageNum && $_start>1){  
            $_start = $_start - ($_pageNum-$_curPageNum);
            $_start = $_start<1 ? 1 : $_start;
            $_curPageNum = $_end-$_start+1;
        }
        //右邊調整
        if($_curPageNum<$_pageNum && $_end<$pages){ 
            $_end = $_end + ($_pageNum-$_curPageNum);
            $_end = $_end>$pages? $pages : $_end;
        }
        //初始化變數
        $_pageHtml = '';
        if(!empty($first)){
            if($_start == 1){
                $_pageHtml .= '<li><a  title="第一頁" href="'.$url.'&page=1">'.$first.'</a></li>';
            }else{
                $_pageHtml .= '<li><a  title="第一頁" href="'.$url.'&page=1">'.$first.'</a></li>';
            }
        }
        if($page>1){
            $_pageHtml .= '<li><a  title="上一頁" href="'.$url.'&page='.($page-1).'">'.$pre.'</a></li>';
        }
        for ($i = $_start; $i <= $_end; $i++) {
            if($i == $page){
                //當前頁
                $_pageHtml .= '<li><a class="current">'.$i.'</a></li>';
            }else{
                //跳轉指定頁
                $_pageHtml .= '<li><a href="'.$url.'&page='.$i.'">'.$i.'</a></li>';
            }
        }
        if(!empty($end)){
          if($_end == $pages){
              $_pageHtml .= '<li><a  title="最後一頁" href="'.$url.'&page='.$pages.'">'.$end.'</a></li>';
          }else{
              $_pageHtml .= '<li><a  title="最後一頁" href="'.$url.'&page='.$pages.'">'.$end.'</a></li>';
          }
        }
        if($page<$_end){
            $_pageHtml .= '<li><a  title="下一頁" href="'.$url.'&page='.($page+1).'">'.$next.'</a></li>';
        }
        //返回分頁資料
        if($pages>1){
            return $_pageHtml;
        }else{
            return null;
        }
    }


}
?>