数据库操作的model类,用到了__call方法
程序员文章站
2022-04-10 12:50:46
...
跳至
[1]
[2]
[全屏预览]
/* 作者 : shyhero 邮箱 : shyhero@outlook.com Q Q : 1757424878 */ 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 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的前景和趋势
推荐阅读
-
用C#对ADO.NET数据库完成简单操作的方法
-
用ADODB来让PHP操作ACCESS数据库的方法
-
扩展c3p0写的通用数据库操作工具类(使用泛型方法)
-
Python操作Oracle数据库的简单方法和封装类实例
-
用C#对ADO.NET数据库完成简单操作的方法
-
Laravel之DB类操作数据库(创建表、添加字段、创建控制器、添加数据、修改数据、删除数据、显示查询数据、返回ID的方法getId)
-
php数据库操作model类(使用__call方法)
-
php实现的简单数据库操作Model类
-
用ADODB来让PHP操作ACCESS数据库的方法_php基础
-
用把逻辑放到工具类的静态方法中而故意弱化model的逻辑有什么好处?