php mysql sql model_php数据库操作model类(使用__call方法)

本文实例讲述了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]['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"));

f68f2add0b68e4f9810432fce46917b7.png

相关标签:php

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值