Simple database operation Model class implemented by php, php database model class
This example describes the simple database operation Model class implemented by php. We will share this with you for your reference. The details are as follows:
This database model class allows you to add, delete, modify, and query databases to simplify database operations.
1. config. php code:
<?php define("HOSTNAME","127.0.0.1"); define("USERNAME","root"); define("PASSWORD",""); define("DATANAME","class");
2. Use the Code:
<? Php/* Author: shyhero */require (". /config. php "); class Model {private $ link; // constructor, initialize the database connection public function _ construct () {$ this-> link = mysqli_connect (HOSTNAME, USERNAME, PASSWORD, DATANAME) or die ("database connection failed"); mysqli_set_charset ($ this-> link, "utf8");} // search for 1. table name 2. condition 3. if no conditions or values are added, query all 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;} // Add 1. table name 2. field to be inserted 3. value: 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);} // modify 1. table name 2. modify Field 3. value 4. condition 5. value: 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_a Ffected_rows ($ this-> link);} // delete 1. table name 2. condition 3. value: 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);} // destructor 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");?>