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

高洛峰
發布: 2023-03-03 14:04:02
原創
1405 人瀏覽過

本文實例講述了php資料庫操作model類別。分享給大家供大家參考,具體如下:

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

程式碼如下:

<?php
define("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][&#39;Field&#39;];
      }
      $this -> zd = $brr;
      return $brr;
    }
    public function __call($name,$value){
      $name = strtolower($name);
      if(array_key_exists($name,$this -> method)){
        if($name == &#39;order&#39;){
          $this -> method[&#39;order&#39;] = " order by ".$value[0];
        }elseif($name == &#39;group&#39;){
        $this -> method[&#39;group&#39;] = " 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[&#39;where&#39;]} {$this -> method[&#39;order&#39;]} {$this -> method[&#39;limit&#39;]} {$this -> method[&#39;group&#39;]} {$this -> method[&#39;having&#39;]}; ";
    }
    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 = &#39;zhu&#39;")->limit("5,10");
  var_dump($a -> find("name"));
登入後複製

   


相關標籤:
php
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!