PHP database operation model class (using __call method)

高洛峰
Release: 2023-03-03 14:04:02
Original
1337 people have browsed it

The example in this article describes the PHP database operation model class. Share it with everyone for your reference, the details are as follows:

This database operation class uses the __call() method to implement the data search function.

The code is as follows:

 "", "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; } }
Copy after login

Usage example:

 where("name = 'zhu'")->limit("5,10"); var_dump($a -> find("name"));
Copy after login


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!