malike 发表于 2018-2-11 12:01:52


            本文实例讲述了php数据库操作model类。分享给大家供大家参考,具体如下:
该数据库操作类使用__call()方法实现了数据的查找功能。
代码如下:
"",
      "order" => "",
      "limit" => "",
      "group" => "",
      "having" => ""
      );
    public function __construct($tableName){
      $this -> tableName = $tableName;
      try{
      $this -> link = mysqli_connect(HOSTNAME,USERNAME,PASSWORD,DATANAME);
      mysqli_set_charset($this -> link,"UTF8");
      }catch(Exception $e){
      echo "数据库连接失败";
      }
      $this -> desc();
    }
    public function __destruct(){
      mysqli_close($this -> link);
    }
    public function desc(){
      $sql = " desc {$this -> tableName}; ";
      $res = mysqli_query($this -> link,$sql);
      $arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
      for($i = 0 ;$izd = $brr;
      return $brr;
    }
    public function __call($name,$value){
      $name = strtolower($name);
      if(array_key_exists($name,$this -> method)){
      if($name == 'order'){
          $this -> method['order'] = " order by ".$value;
      }elseif($name == 'group'){
      $this -> method['group'] = " group by ".$value;
      }else{
          $this -> method[$name] = " {$name} ".$value;
      }
      }else{
      return "the method is not found!";
      }
      return $this;
    }
    public function method(){
      return " {$this -> method['where']} {$this -> method['order']} {$this -> method['limit']} {$this -> method['group']} {$this -> method['having']}; ";
    }
    public function find($a="*"){
      if(in_array("{$a}",$this -> zd) || $a == "*"){
      $sql = "select {$a} from {$this -> tableName} {$this -> method()} ";
      }else{
      $sql = "select * from {$this -> tableName}";
      }
      //return $sql;
      $res = mysqli_query($this -> link,$sql);
      $arr = mysqli_fetch_all($res,MYSQLI_ASSOC);
      return $arr;
    }
}
页: [1]
查看完整版本: php数据库操作model类(使用__call方法)