基於PHP MySQLi擴展的數據庫操做Model

<?php
/*****************************
Model類(使用MySQL擴展訪問數據庫)
******************************/
class Model{
    private $table;
    //數據庫連接
    private $link;
    //最後一次執行的sql語句
    private $sql;
    private $tableString;
    private $fieldString;
    private $whereString;
    private $orderString;
    private $limitString;

    //初始化類
    public function __construct($tableName){
        $dbinfo=array(
            'hostname'=>'',
            'username'=>'',
            'password'=>'',
            'database'=>''
        );
        $this->link=new mysqli($dbinfo['hostname'],$dbinfo['username'],$dbinfo['password'],$dbinfo['database']);
        if($this->link->connect_errno)
            trigger_error('Error:Could not make a database link ('.$this->link->connect_errno.')'.$this->link->connect_errno);
        $this->link->set_charset("utf8");
        $this->fieldString='*';
        $this->tableString=$tableName;
        $this->leftJoinString='';
        $this->whereString='';
        $this->orderString='';
        $this->limitString='';
    }
 

    /********封裝的MySQLI擴展方法********/

    //參數過濾,輸入參數只能是基本類型或一維數組
    public function escape($param){
        if(is_array($param)){
            foreach ($param as $key => $value) {
                $param[$key]=$this->link->real_escape_string($value);
            }
        }else{
            $param=$this->link->real_escape_string($value);
        }
        return $param;
    }

    //獲取插入後生成的ID
    public function getLastId(){
        return $this->link->insert_id;
    }

    //獲取影響的行數
    public function countAffected(){
        return $this->link->affected_rows;
    }

    //執行SQL命令返回TRUE或FALSE
    public function execute($sql){
        $this->sql=$sql;
        $result=$this->link->real_query($this->sql);
        if(false===$result){
            trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
            return false;
        }else{
            $sql=strtolower($this->sql);
            return (false===strpos($sql,'insert')?true:$this->link->insert_id;//若是包含insert就返回插入記錄的ID
        }
    }

    //執行SQL查詢返回關聯數組
    public function query($sql){
        $result=$this->link->real_query($sql);
        $this->sql=$sql;
        if($result!==false){
            $record=array();
            $list=array();
            while($record=$result->fetch_assoc()){
                $list[]=$record;
            }
            return $list;
        }else{
            trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
            return false;
        }
    }

    /********單表增刪查改********/
    public function create($table,$model){
        $fields='';
        $values='';
        foreach ($model as $key => $value) {
            if($fields){
                $fields.=',';
            }
            $fields.="`$key`";
            if($values){
                $values.=',';
            }
            $values.=is_numeric($value)?$value:"'".$this->link->real_escape_string($value)."'";
        }
        $this->sql="INSERT INTO `$table`($fields) VALUES($values)";
        if(false===$this->link->real_query($this->sql))
            trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
        return $this->link->insert_id;
    }

    public function modify($table,$model,$where){
        $assins='';
        $where=$this->rewhere($where);
        foreach ($model as $key => $value) {
            $rkey=$this->link->real_escape_string($key);
            $rvalue=$this->link->real_escape_string($value);
            if(!is_numeric($rvalue)){
                $rvalue="'".$rvalue."'";
            }
            $assins.=$assins?",`$rkey`=$rvalue":"`$rkey`=$rvalue";
        }
        $result=$this->link->real_query($this->sql);
        if(false===$result)
             trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
    }

    public function remove($table,$where){
        $where=$this->rewhere($where);
        $this->sql="DELETE FROM `$table` WHERE $where";
        $result=$this->link->real_query($this->sql);
        if(false===$result)
             trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
        return $flag;
    }

    public function unique($where){
        $where=$this->rewhere($where);
        $this->sql="SELECT * FROM `$table` WHERE $where LIMIT 1";
        $result=$this->link->real_query($this->sql);
        if($result===false)
            trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
        return $result -> fetch_object();
    }

    public function countRow($where){
        $where=$this->rewhere($where);
        $this->sql=($where=='')?"SELECT COUNT(*) as 'totalRow' FROM `{$this->tableString}`":"SELECT COUNT(*) FROM `{$this->tableString}` WHERE $where";
        $result=$this->link->real_query($this->sql);
        if($result===false)
            trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
        $record=$result->fetch_Object();
        return $record->totalRow;
    }

    //按條件查找函數
    public function search($table,$fields,$leftJoin='',$where='',$order='',$limit=''){
        if(is_array($fields))
            $fields=implode(",",$fields);
        $this->sql=empty($fields)?"SELECT * FROM `$table`":"SELECT $fields FROM `$table`";
        if(!empty($where)){
            $where=$this->rewhere($where);
            $this->sql.=" WHERE $where";
        }
        if(!empty($order))
            $this->sql.=" ORDER BY $order";
        if(!empty($order))
            $this->sql.="LIMIT $limit";
        $result=$this->link->real_query($this->sql);
        if($result===false){
             trigger_error('<br/>ERROR MESSAGE:'.$this->link->error.'<br/>THE SQL:'.$this->sql);
        }else{
            $tempItem=array();
            $tempList=array();
            while($tempItem=$result -> fetch_assoc()){
                if(!empty($tempItem['create_time']))
                    $tempItem['create_time_exp']=date('Y-m-d H:i:s',$tempItem['create_time']);
                if(!empty($tempItem['add_time']))
                    $tempItem['add_time_exp']=date('Y-m-d H:i:s',$tempItem['end_time']);
                if(!empty($tempItem['start_time']))
                    $tempItem['start_time_exp']=date('Y-m-d H:i:s',$tempItem['start_time']);
                if(!empty($tempItem['end_time']))
                    $tempItem['end_time_exp']=date('Y-m-d H:i:s',$tempItem['end_time']);
                $tempList[]=$tempItem;
            };
            return $tempList;
        }
    }

    public function keyIn($ids){
        if(!empty($ids)){
            return false;
        }
        if(is_array($ids)){
            foreach ($ids as $key => $value) {
                $ids[$key]=$this->link->real_escape_string($value);
            }
            $ids=implode(',',$ids);
        }else{
            $ids=$this->link->real_escape_string($ids);
        }
        $primary=$this->getPrimaryKey();
        if(!empty($this->whereString))
            $this->whereString.=" AND ";
        $this->whereString.="`$primary` in ($ids)";
        return $this;
    }


/******************仿ThinkPHP的鏈式操做*******************************/
    //設置查詢的字段
    public function field($field){
        if(is_array($field))
            $field=implode(',',$field);
        $this->fieldString=$field;
        return $this;
    }

    public function table($table){
        $this->tableString=$table;
    }

    public function order($order){
        $this->orderString=$order;
    }

    public function limit($limit){
        $this->limitString=$limit;
    }
    //將數組格式的條件組裝成字符串
    public function where($where){
        if(is_array($where)&&count($where)>0){
            $str='';
            foreach($where as $key=>$value){
                if(!empty($str)){
                    $str.=' AND ';
                }
                $rekey=$this->link->real_escape_string($key);
                $revalue=$this->link->real_escape_string($value);
                $str.=is_numeric($revalue)?"`$rekey`=$revalue":"`$rekey`='$revalue'";
            }
            $this->whereString=$str;
        }else{
            $this->whereString=$where;
        }
        return $this;
    }

    //刪除
    public function delete(){
        if(empty($this->whereString))
            trigger_error('<br/>ERROR MESSAGE:刪除條件不能夠是空');
        $this->sql="DELETE FROM {$this->tableString} WHERE {$this->whereString}";
    }

    //更新
    public function update($model){
        if(empty($this->whereString))
            trigger_error('<br/>ERROR MESSAGE:更新條件不能夠是空');
        if(empty($model)||count($model)==0)
            trigger_error('<br/>ERROR MESSAGE:更新參數不能夠是空')
        $assins='';
        foreach ($model as $key => $value) {
            $rkey=$this->link->real_escape_string($key);
            $rvalue=$this->link->real_escape_string($value);
            if(!is_numeric($rvalue)){
                $rvalue="'".$rvalue."'";
            }
            $assins.=$assins?",`$rkey`=$rvalue":"`$rkey`=$rvalue";
        }
        $this->sql="UPDATE {$this->tableString} SET $assins WHERE {$this->whereString}";
    }

    //查詢
    public function select(){
        $this->sql="SELECT {$this->fieldString} FROM {$this->tableString}";
        if(!empty($this->whereString)) $this->sql.=' WHERE '.$this->whereString;
        if(!empty($this->orderString)) $this->sql.=' ORDER BY '.$this->orderString;
        if(!empty($this->limitString)) $this->sql.=' LIMIT '.$this->limitString;
        return $this->query($this->$sql);
    }

    /*開發環境用於調試的語句,生產環境能夠刪除*/
    public function getSql(){
        return $this->sql;
    }
}
相關文章
相關標籤/搜索