首頁 > php教程 > PHP源码 > 簡單資料庫操作的Model類

簡單資料庫操作的Model類

WBOY
發布: 2016-08-18 08:57:52
原創
990 人瀏覽過
跳至 [1] [2] [全螢幕預覽]
<?php
	define("HOSTNAME","127.0.0.1");
	define("USERNAME","root");
	define("PASSWORD","");
	define("DATANAME","class");
登入後複製

2. [代碼][PHP]代碼     跳至 [1] [2] [全螢幕預覽]

<?php
	/*
		作者:shyhero
		邮箱:shyhero@outlook.com
		Q  Q: 1757424878
	 */
	require("./config.php");
	class Model{
		private $link;
		//构造函数,初始化数据库连接
		public function __construct(){
			$this -> 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="",$key="",$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="",$key="",$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","name","dujianing","id","1"));
	//var_dump($m -> del("stu","name","li"));

?>
登入後複製
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
最新問題
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板