本文实例讲述了php数据库操作model类。分享给大家供大家参考,具体如下:
该数据库操作类使用__call()方法实现了数据的查找功能。
代码如下:
<?php
/*
作者 : shyhero
*/
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"));
更多关于php相关内容感兴趣的读者可查看本站专题:《php+mysql数据库操作入门教程》、《php基于pdo操作数据库技巧总结》、《php+mongodb数据库操作技巧大全》、《php+oracle数据库程序设计技巧总结》、《php+mssql数据库程序设计技巧总结》、《php+redis数据库程序设计技巧总结》、《php+mysqli数据库程序设计技巧总结》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!