本文实例讲述了PHP实现的简单数据库操作Model类。分享给大家供大家参考,具体如下:
PHP;">
PHP
define("HOSTNAME","127.0.0.1");
define("USERNAME","root");
define("PASSWORD","");
define("DatanAME","class");
2. 使用代码:
PHP;">
link = MysqLi_connect(HOSTNAME,USERNAME,PASSWORD,DatanAME) or die("数据库连接失败");
MysqLi_set_charset($this -> link,"utf8");
}
//查找 1.表名 2.条件 3.值 如果不添加条件或者值,就全部查询
public function find($table="",$key="",$value=""){
if(!$key||!$value){
$sql = "select * from {$table}";
}else{
$sql = "select * from {$table} where {$key} = '{$value}'";
}
$res = MysqLi_query($this -> link,$sql);
$arr = MysqLi_fetch_all($res,MysqLI_ASSOC);
MysqLi_free_result($res);
return $arr;
}
//增加 1.表名 2.需要插入的字段 3.值1
public function ins($table="",$zd="name,score",$value=""){
$arr = explode(",",$value);
$str = "";
foreach($arr as $k => $v){
$str .= "'".$v."'".",";
}
$str = rtrim($str,");
$sql = "insert into {$table}({$zd})values({$str})";
$res = MysqLi_query($this -> link,$sql);
return MysqLi_insert_id($this -> link);
}
//修改 1.表名 2.修改字段 3.值 4.条件 5.值
public function upd($table="",$value="",$key2="",$value2=""){
$sql = "update {$table} set {$key}='{$value}' where {$key2}='{$value2}'";
$res = MysqLi_query($this -> link,$sql);
return MysqLi_affected_rows($this -> link);
}
//删除 1.表名 2.条件 3.值
public function del($table="",$value=""){
$sql = "delete from {$table} where {$key}='{$value}'";
$res = MysqLi_query($this -> link,$sql);
return MysqLi_affected_rows($this -> link);
}
//析构函数
public function __destruct(){
if(isset($res))
MysqLi_free_result($res);
MysqLi_close($this -> link);
}
}
$m = new Model();
//var_dump($m -> find("stu","id"));
var_dump($m -> ins("stu","name","zhu"));
//var_dump($m -> upd("stu","dujianing","id","1"));
//var_dump($m -> del("stu","li"));
?>
更多关于PHP相关内容感兴趣的读者可查看本站专题:《》、《》、《》、《》、《》、《》、《》及《》
希望本文所述对大家PHP程序设计有所帮助。
原文链接:https://www.f2er.com/php/18494.html