This article mainly introduces the PHP implementation of the simple database operation model class, combined with the example form analysis of PHP database operation models of the definition and use of skills, including the basic database additions and deletions and other functions, the need for friends can refer to the next
The database model class can be used to make database additions and deletions and simplify database operation.
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, initializing database connection public function __construct () {$this-link = mysqli_connect (hostname,username,password,dataname) o R die ("Database connection failed"); Mysqli_set_charset ($this-Link, "UTF8"); }//Find 1. Table Name 2. Condition 3. If you do not add a condition or value, all queries 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 3 to be inserted. 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 = "", $key 2= "", $value 2= "") {$sql = "Update {$ta BLE} set {$key}= ' {$value} ' where {$key 2}= ' {$value 2} '; $res = mysqli_query ($this-Link, $sql); Return mysqli_affected_rows ($this, link); }//delete 1. Table Name 2. Condition 3. Value Public Function del ($table = "", $key = "", $value = "") {$sql = "delete from {$table} where {$key}= ' {$va Lue} ' "; $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")); >
The above is the whole content of this article, I hope that everyone's study has helped.