您好,登錄后才能下訂單哦!
這篇文章主要介紹php如何實現簡單數據庫操作Model類,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
該數據庫模型類可實現數據庫的增刪改查,簡化數據庫操作。
1. config.php代碼:
<?php define("HOSTNAME","127.0.0.1"); define("USERNAME","root"); define("PASSWORD",""); define("DATANAME","class");
2. 使用代碼:
<?php /* 作者:shyhero */ 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如何實現簡單數據庫操作Model類”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。