php資料庫操作model類(使用__call方法)

來源:互聯網
上載者:User
本文執行個體講述了php資料庫操作model類。分享給大家供大家參考,具體如下:

該資料庫操作類使用__call()方法實現了資料的尋找功能。

代碼如下:

<?phpdefine("HOSTNAME","127.0.0.1");define("USERNAME","root");define("PASSWORD","");define("DATANAME","class");class Model{    private $link;    private $tableName;    private $zd;    private $method = array(      "where" => "",      "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 ;$i < count($arr);$i++){        $brr[] = $arr[$i]['Field'];      }      $this -> zd = $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[0];        }elseif($name == 'group'){        $this -> method['group'] = " group by ".$value[0];        }else{          $this -> method[$name] = " {$name} ".$value[0];        }      }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;    }}

用法樣本:

<?php  function __autoload($className){    require($className.".class.php");  }  $a = new Model("stu");  $a -> where("name = 'zhu'")->limit("5,10");  var_dump($a -> find("name"));
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.