登录  /  注册
首页 > php教程 > PHP源码 > 正文

数据库操作的model类,用到了__call方法

php中文网
发布: 2016-08-22 10:13:31
原创
1059人浏览过
跳至 [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;
		}
	}
登录后复制

2. [代码][PHP]代码 跳至 [1] [2] [全屏预览]

	function __autoload($className){
		require($className.".class.php");
	}

	$a = new Model("stu");
	$a -> where("name = 'zhu'")->limit("5,10");
	var_dump($a -> find("name"));
登录后复制
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 技术文章
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2023 //m.sbmmt.com/ All Rights Reserved | 苏州跃动光标网络科技有限公司 | 苏ICP备2020058653号-1

 | 本站CDN由 数掘科技 提供

登录PHP中文网,和优秀的人一起学习!
全站2000+教程免费学